Does mongoose findOne on model return a promise?

后端 未结 1 1550
一个人的身影
一个人的身影 2021-01-06 03:02

I have a simple Node module that exports a function that makes a database query. The problem is that this function returns before the database query completes.



        
相关标签:
1条回答
  • 2021-01-06 03:33

    Because findOne is async function, one way to return from it is through callback function

    module.exports.isAdmin = function(user_id, callback) {
      var params = {'roles': 'admin'};
    
      dao.findOne(params, function(err, user) {
        if (err) {
          logger.error(err);
          callback && callback(false);
        }
        if (_.indexOf(user.roles, 'admin') != -1) {
          logger.info("admin user: " + user._id);
          if (user._id == user_id)
              callback && callback(true);
        }
        callback && callback(true);
      });
    };
    
    isAdmin(userId, function(v) {
        console.log(v);
    })
    

    Another way is to get Promise in findOne, as this doc said, .exec() gives you a fully-fledged promise. Even with Promise, to meet you requirement, the result could be returned through callback function.

    module.exports.isAdmin = function(user_id, callback) {
      var params = {'roles': 'admin'};
    
      var queryPromise = dao.findOne(params).exec();
      queryPromise.then(function(user) {
          if (_.indexOf(user.roles, 'admin') != -1) {
            logger.info("admin user: " + user._id);
            if (user._id == user_id)
              callback && callback(true);
          }
        }, function(err) {
          callback && callback(false);
      });
    };
    
    0 讨论(0)
提交回复
热议问题