Set Variable to result of Mongoose Find

后端 未结 3 677
余生分开走
余生分开走 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);
    
    });
    

提交回复
热议问题