【问题标题】:Mongoose Promise not passing data to next chainMongoose Promise 不会将数据传递到下一个链
【发布时间】:2025-12-10 18:45:02
【问题描述】:

我正在使用 mongoose 查询 MongoDB。结果只能在第一个.then(function(results){ // can send the result from here..}) 中访问。但是当我操纵结果并将其传递给下一个.then()chain 时,它是不可访问的。下面是完整的功能。

exports.getAcl = function(req, res) {

  User.findAsync({}, {
    acl: 1
  })
  .then(function(results){
    var aclList = [];
    results.forEach(function(result,index,arr){
      aclList[result._id] = result;
      if (index === (arr.length - 1)) {
        console.log('I can log the aclList here..', aclList)
        return aclList // But neither able to send it to next chain nor to front end res.send(aclList) 
      }
    })
  })
  .then(function(aclList){
    console.log(aclList) // Loging undefined
    res.status(200).json(aclList); // undefined
  })
  .catch(handleError(res));
}

请让我知道我在这里做错了什么......谢谢

【问题讨论】:

  • findAsync 来自哪里?它不在猫鼬中。
  • @kyrylkov 我正在使用蓝鸟和猫鼬。 var mongoose = require('bluebird').promisifyAll(require('mongoose'));
  • @Jasnan:新版本的猫鼬也支持开箱即用的承诺
  • @Jasnan Mongoose 4 find 返回一个具有then 方法mongoosejs.com/docs/queries.htmlQuery

标签: javascript node.js mongoose promise bluebird


【解决方案1】:

代替

results.forEach(function(result,index,arr){
  aclList[result._id] = result;
  if (index === (arr.length - 1)) {
    console.log('I can log the aclList here..', aclList)
    return aclList // But neither able to send it to next chain nor to front end res.send(aclList) 
  }
})

试试

var resArray = [];
results.forEach(function(result,index){
  aclList[result._id] = result;
  if (index === (arr.length - 1)) {
    newRes.push(aclList);
  }
})
// console.log(resArray) to verify they are there
return resArray;

底线:不要对每个函数使用多个返回(如forEach)。

【讨论】:

  • 嗨..它仍然没有工作。感谢您的底线提示。我用.map 替换了forEach 方法,现在它可以工作了。