Javascript 节点q通过数组循环并附加daata

Javascript 节点q通过数组循环并附加daata,javascript,node.js,q,Javascript,Node.js,Q,假设我有以下数组: [{id: 1, name: 'Hello', otherTableId: 2}]; 现在,我希望遍历所有这些数组,并从我的mongodb中获取一些数据,这些数据将附加到一个新数组中,然后返回 我将如何使用q来实现这一点 以下是我目前拥有的,但我不知道用什么替换foreach: 我的模式 我想返回的基本内容是对话及其用户的列表 如下所示:[{conversation\u id:String,userOne:Object,userTwo:Object}] 但是我不确定这是否可

假设我有以下数组:

[{id: 1, name: 'Hello', otherTableId: 2}];
现在,我希望遍历所有这些数组,并从我的mongodb中获取一些数据,这些数据将附加到一个新数组中,然后返回

我将如何使用q来实现这一点

以下是我目前拥有的,但我不知道用什么替换foreach:

我的模式

我想返回的基本内容是对话及其用户的列表

如下所示:[{conversation\u id:String,userOne:Object,userTwo:Object}]


但是我不确定这是否可行?

首先,在猫鼬中,您内置了种群逻辑,这意味着您应该能够添加如下内容:

conversation
.find({users: {$all: [req.query.id]})
.populate('otherTableId')
.exec(function (err, conversations) {
  // now the convesations array should have followed the link from 'otherTableId' if you have defined the ref in the schema.
})
如果我把这个问题解释得更一般一些,我想你是在问Promise库Q,它应该支持Promise.all方法。我正在使用下面的标准ES6实现,但请在Q中找到相应的方法

const ids = [1,2,3,4]
const promises = ids.map(id => mongoose.models.childTable.findOne(id))
Promise.all(promises).then(array => {
   // here you will find the array containing the objects
})

嗨,克里斯蒂安,谢谢你的回复。我添加了一些我的代码基础,也许你可以看看?对话模式应该有一个对用户模式的引用。查询对话时,应使用“填充”命令直接包含用户对象。请查看此页面以了解发生了什么:它有一个对用户架构的引用,但以数组的形式。对话中用户数组中的每个用户都是用户表中用户的id。您应该在定义中包括架构的名称-即用户:[models.user]
conversation
.find({users: {$all: [req.query.id]})
.populate('otherTableId')
.exec(function (err, conversations) {
  // now the convesations array should have followed the link from 'otherTableId' if you have defined the ref in the schema.
})
const ids = [1,2,3,4]
const promises = ids.map(id => mongoose.models.childTable.findOne(id))
Promise.all(promises).then(array => {
   // here you will find the array containing the objects
})