Set Variable to result of Mongoose Find

后端 未结 3 676
余生分开走
余生分开走 2021-01-01 00:37

I\'m trying to do something like this

    function retrieveUser(uname) {
      var user = User.find({uname: uname}, function(err, users) {
        if(err)
           


        
相关标签:
3条回答
  • 2021-01-01 01:25

    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);
    
    });
    
    0 讨论(0)
  • 2021-01-01 01:37

    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
    });
    
    0 讨论(0)
  • 2021-01-01 01:40

    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
    }
    
    0 讨论(0)
提交回复
热议问题