Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Variable to result of Mongoose Find

I'm trying to do something like this

    function retrieveUser(uname) {
      var user = User.find({uname: uname}, function(err, users) {
        if(err)
          console.log(err);
          return null;
        else
          return users[0];
      return user;

But this returns a document instead of a user object. The parameter users is an array of user objects matching the query, so how would I store one of the objects into a variable that my function could return?

like image 395
mao3 Avatar asked Sep 21 '13 22:09

mao3


People also ask

What does find () return in Mongoose?

What is find() in Mongoose? Mongoose's find() method is a query to retrieve a document or documents that match a particular filter.

Does find return an array Mongoose?

and it will return array? find returns an array always.

What does exec () do Mongoose?

In mongoose, exec method will execute the query and return a Promise.

Can I use $in in Mongoose?

We can specify as many conditions in the query field. But in cases, where we need to filter according to only one field but more than on values. For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator.


2 Answers

The function User.find() is an asynchronous function, so you can't use a return value to get a resultant value. Instead, use a callback:

function retrieveUser(uname, callback) {
  User.find({uname: uname}, function(err, users) {
    if (err) {
      callback(err, null);
    } else {
      callback(null, users[0]);
    }
  });
};

The function would then be used like this:

retrieveUser(uname, function(err, user) {
  if (err) {
    console.log(err);
  }

  // do something with user
});
like image 105
hexacyanide Avatar answered Sep 27 '22 17:09

hexacyanide



Updated on 25th Sept. 2019

Promise chaining can also be used for better readability:

Model
.findOne({})
.exec()
.then((result) => {
   // ... rest of the code
   return Model2.findOne({}).exec();
})
.then((resultOfModel2FindOne) => {
   // ... rest of the code
})
.catch((error) => {
   // ... error handling
});

I was looking for an answer to the same question.

Hopefully, MongooseJS has released v5.1.4 as of now.

Model.find({property: value}).exec() returns a promise.

it will resolve to an object if you use it in the following manner:

const findObject = (value) => {
  return Model.find({property: value}).exec();
}

mainFunction = async => {
     const object = await findObject(value);
     console.log(object); // or anything else as per your wish
}
like image 41
retr0 Avatar answered Sep 27 '22 18:09

retr0