Store documentId as field in document - javascript

I want to store the documentId created in collection as the field/property as docid in the same document. I am using cloud firestore.
It is showing error "ReferenceError: doc is not defined"
whenever I try and store the doc.id
db.collection("Colleges").doc(user.uid).collection('Internships').doc().set({
CompanyName :this.I_company,
InternshipTitle : this.I_title,
duration: this.duration,
amount:this.I_amount,
week:this.week,
docid: doc.id
})

Indeed, a call to the doc() method of a CollectionReference without any path will return a DocumentReference with "an automatically-generated unique ID".
But you have to do as follows: first get the new DocumentReference, then use the set() method on this DocumentReference.
var docRef = db.collection("Colleges").doc(user.uid).collection('Internships').doc();
docRef.set({
CompanyName :this.I_company,
InternshipTitle : this.I_title,
duration: this.duration,
amount:this.I_amount,
week:this.week,
docid: docRef.id
})
However, you may double check if you really need to write the docRef.id in a specific field of the document, because in any case you can get it later with the id property.

Related

insert id into type array mongodb

My mongodb collection login is structured as so:
email: "John.doe#gmail.com"
password: "password"
full_name: "John Doe"
list_of_docs_bought: Array
0: "g81h8"
1: "fursr"
now, in my code, what I want to do is insert a new id into the list_of_docs_bought array. My code is as follows:
let collection = database.collection('login')
let doc = collection.updateOne({ email: req.session.username }, {$set: { list_of_docs_bought: '2xx729' }})
however, this isn't going to work because I need to essentially insert a new id into there, not update it. But if I use .insert(), I am not sure if that is going to work because it will insert a totally new record instead of just into the array. Can anyone offer some help?
You can use upsert which does exactly what you need.
Explanation below is taken from the official docs.
Creates a new document if no documents match the filter. For more details see upsert behavior.
Updates a single document that matches the filter.
So you would need to change your code to that:
let doc = collection.updateOne({ email: req.session.username }, {$push: { list_of_docs_bought: '2xx729' }}, { upsert: true })
Edit: You need to use the $push operator in order to add an element in an array. The $set operator will just overwrite it.

Using root object in graphql resolver function to access parent fields properties

I am using neo4j-graphql-js library to auto generate resolvers from the schema. For a node in the schema(Employee) i need to get a particular node property(empid) from a rest call as we plan to remove that property from our neo4j database due to privacy issues. I am trying to write a custom resolver for that field . I have added #neo4j directive to that field in the schema for neo4j to ignore it. I need to make a rest call that accepts a parameter named uid and returns the corressponding empid. This iuid is a property of Employee node and so is present in my neo4j DB.
The issue is while writing the resolver the root objects only holds the filed values accesed in the query. So if iuid is not part of the query i'm unable to get it's value in the root obj.
Here is my employee node: -
type Employee{
empId: String #neo4j_ignore
buCode: String
iuid: String
name: String
projectCode: String
roleCode: String
grade: String
mailid: String
duCode: String
txtmailid_new: String
Here is my resolver where for my i am returning a dummy string instead of making a rest call: -
const resolvers={
Employee: {
empId: async (obj, params, ctx, resolveInfo) => {
console.log(obj.iuid);
var result="dummy_emp_id";
return result;
}
}
};
const schema = makeAugmentedSchema({ typeDefs, resolvers} );
const server = new ApolloServer({ schema, context: { driver } });
server.listen(3003, '127.0.0.1').then(({ url }) => {
console.log(`GraphQL API ready at ${url}`);
});
Here is my query:-
{
Employee(first : 10)
{
empId
name
}
}
I want to access all the value of all the field of the employee node so i can get the iuid.The console log returns undefined as the root object only has the queried field. I don't know even if it is possible and if not is there any workaround this?

mongo db query check that no other document with matched values exist

I want to create a query with which I can check if a document has related documents, e.g. I have a document
{
name:"test1",
status:"CREATED"
date:"2018-12-12"
user:"foo"
}
and i want to retreive all documents where the user has no document with status:"OPEN"
I had the idea to project a field with the number of documents which are open for the user & day and filter for 0, but I don't know how I could do that.
So when i have the following documents:
it should only return foo2 and foo4 because foo, foo3 and foo5 already have documents with status:"OPEN"
Please find the below code to get all the documents for users for whom no 'OPEN' status exists:
db.collection.find({
user: {
$nin: db.collection.find({status: 'OPEN'}).map((row) => row.user)
}
});
$nin: to specify and exclusion list.
.map((row) => row.user): to convert array of filtered documents to array of just the string containing user ids.
Here is the logic:
1.First query all the doc with status OPEN
2.Now you have a sets of data with OPEN only doc
4.Now create a query where you pass all the userId of this set in query and fetch those values from collection which have userId not equal to the passed ones
Example:
db.collectionName.find({status:'OPEN'});// set1
db.collectionName.find({userId:{$not : 'userid1'}},{userId:{$not : 'userid2'}},....);
This is not good code but this is all you can do now or add some other fields in db to do it more effectively

Is it possible to get document id of collections available in Firebase Cloud Firestore database?

I want to get the document id of societies collection in cities collection but my code returns a different id in societyId field in the cities collection.
myId: string = "";
private docRef: firebase.firestore.DocumentReference;
this.docRef = firebase.firestore().collection("societies").doc();
this.myId = this.docRef.id;
this.cityList = firebase.firestore().collection("cities").add({
cityName: this.city,
societyId: this.myId
}).then((doc) => {
console.log(doc);
}).catch((err) => {
console.log(err);
});
You are getting another societyId, which is different than the id that is generated by simply calling doc() function because you are adding an object to the database using CollectionReference's add() function:
Adds a new document to this collection with the specified data, assigning it a document ID automatically.
Instead of using DocumentReference's set() function:
Writes to the document referred to by this DocumentReference. If the document does not exist yet, it will be created. If you pass options, the provided data can be merged into the existing document.
According to your comment, if you want to have the same id, please change the following line of code:
this.cityList = firebase.firestore().collection("cities").add(/* ... */);
to
this.cityList = firebase.firestore().collection("cities").doc(this.myId).set(/* ... */);

How to get firebase id

Anyone know how to get the Firebase unique id? I've tried name(), name, key, key(). Nothing works.
I am able to see the data but I have no idea how to get the id back. I need it.
//Create new customers into firebase
function saveCustomer(email) {
firebase.database().ref('/customers').push({
email: email
});
firebase.database().ref('/customers').on("value", function(snapshot) {
console.log(snapshot.val());
console.log(snapshot.value.name());
}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
The call to push will return a Firebase reference. If you are using the Firebase 3 API, you can obtain the unique key of the pushed data from the reference's key property:
var pushedRef = firebase.database().ref('/customers').push({ email: email });
console.log(pushedRef.key);
The key for the pushed data is generated on the client - using a timestamp and random data - and is available immediately.
Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it.
The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated:
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();
Documentation.
but this method won't work when you also need the id beforehand
for example to save it in the database itself.
Firebase suggests this:
// Add a new document with a generated id.
var newCityRef = db.collection("cities").doc();
--for some reason, push() and key() didn't work for me. also in this case the reference contains the whole path. so need a different method for getting the id.
Doing this below helped to get the id from the reference and use it.
const ref = db.collection('projects').doc()
console.log(ref.id) // prints the unique id
ref.set({id: ref.id}) // sets the contents of the doc using the id
.then(() => { // fetch the doc again and show its data
ref.get().then(doc => {
console.log(doc.data()) // prints {id: "the unique id"}
})
})

Categories

Resources