Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return query results to a variable using mongoose

I am still in learning stage of Node.js and Moongoose and i have a scenario where in

  • I am taking value(ABC) from form submit.It is a user's Name
  • Then i am searching for that name in users collection(User)
  • Fetch that user and write its ObjectID in another schema(article) using ref.

My logic:

article.owner = User.findOne({ 'name' : 'ABC' })
    .exec(function (err, user){
         return user
    })

But it is not returning results. I referred some other answers and tried async.parallel but still i am not able to save ABC user's objectID in article schema at article.owner i am always getting null.

Please suggest me any other better ways.

like image 334
user3122051 Avatar asked Dec 20 '13 09:12

user3122051


People also ask

What does findById return in Mongoose?

findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .

What is __ V in MongoDB?

What is __ V in MongoDB collection? Posted On: Jun 24, 2021. In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.24-Jun-2021.

Can I use $in in Mongoose?

For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection. For performing HTTP endpoint testing, we will use the postman tool.

What does Mongoose Exec return?

exec() function returns a promise, that you can use it with then() or async/await to execute a query on a model "asynchronous".


2 Answers

When Node has to do any I/O, like reading from a database, it will be done asynchronously. Methods like User.findOne and Query#exec will never return a result upfront so article.owner will not be properly undefined in your example.

The result of an asynchronous query will only be available inside of your callback, which is only invoked when your I/O has finished

article.owner = User.findOne({ name : 'ABC' }) .exec(function (err, user){    
    // User result only available inside of this function!
    console.log(user) // => yields your user results
})

// User result not available out here!
console.log(article.owner) // => actually set to return of .exec (undefined)

What asynchronous code execution means in the above example: When Node.js hits article.owner = User.findOne... it will execute User.findOne().exec() and then move straight onto console.log(article.owner) before .exec has even finished.

Hope that helps clarify. It takes a while to get used to async programming it but it will make sense with more practice

Update To answer your specific problem, one possible solution would be:

User.findOne({name: 'ABC'}).exec(function (error, user){
    article.owner = user._id; // Sets article.owner to user's _id
    article.save()            // Persists _id to DB, pass in another callback if necessary
});

Remember to use Query#populate if you want to load your user with the article like so:

Article.findOne({_id: <some_id>}).populate("owner").exec(function(error, article) {
    console.log(article.owner); // Shows the user result
});
like image 114
C Blanchard Avatar answered Sep 27 '22 19:09

C Blanchard


User.findOne({ 'name' : 'ABC' }) .exec(function (err, user){
    article.owner = user.fieldName;
})
like image 30
damphat Avatar answered Sep 27 '22 21:09

damphat