Monday 12 June 2017

Node.js forEach inside mongoose findOne query

I have a document Users with storage property defined as an array of ObjectId referenced to other document called Storage. I'm trying to get a specific user and then return the storage information inside an array.

This is my code:

module.exports.storageDetail = function(req, res) {
      User.findOne({'userId': req.user.userId}, 'storages').then(function(data){
        var storageArray = [];

        data.storages.forEach(function(record){
          Storage.findOne({_id: record}, function(err, storage){
            storageArray.push(storage);
          });
        });

        return Promise.all(storageArray);
      }).then(function(storageList){
        res.render('storage_template', {
          storage: storageList
        });
        console.log(storageList);
      });
}

But after execution, storageList is an empty array.

I'm a newbie to node.js and please let me know if I need to provide more information.



via Valip

No comments:

Post a Comment