mao3
mao3

Reputation: 65

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?

Upvotes: 6

Views: 23602

Answers (3)

retr0
retr0

Reputation: 744


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
}

Upvotes: 4

Vrushabh Ranpariya
Vrushabh Ranpariya

Reputation: 376

Basically, MongoDB and NodeJS have asynchronous functions so we have to make it to synchronous functions then after it will work properly as expected.

router.get('/', async function(req, res, next) {

  var users = new mdl_users();
      var userData = []; // Created Empty Array
      await mdl_users.find({}, function(err, data) {
        data.forEach(function(value) {
          userData.push(value);
        });
      });
  res.send(userData);

});

In Example, mdl_users is mongoose model and I have a user collection(table) for user's data in MongoDB database and that data storing on "userData" variable to display it.In this find function i have split all documents(rows of table) by function if you want just all record then use direct find() function as following code.

router.get('/', async function(req, res, next) {

  var users = new mdl_users();
  var userData = await mdl_users.find();
  res.send(userData);

});

Upvotes: 2

hexacyanide
hexacyanide

Reputation: 91609

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
});

Upvotes: 21

Related Questions