节点q循环遍历数组并追加数据
Node q loop through array and append data
假设我有以下数组:
[{id: 1, name: 'Hello', otherTableId: 2}];
现在我希望遍历所有这些数组并从我的 MongoDB 中获取一些数据,我想将这些数据附加到一个新数组,然后 returned.
我如何使用 q
执行此操作?
这是我到目前为止的内容,但我不知道用什么来替换 foreach
:
router.route('/api/conversations')
.get(function (req, res) {
mongoose.models.conversation.find({users: {$all: [req.query.id]}}, function (err, conversation) {
if (err) {
res.status(500).send(err)
}
else {
var returnArray =[];
conversation.forEach(function (x) {
})
}
});
});
我的架构
var conversation = mongoose.Schema({
users: Array
});
var user = mongoose.Schema({
username: String,
password: String,
firstname: String,
lastname: String,
is_active: Boolean,
user_type: Number
});
我想要的 return 基本上是对话及其用户的列表。
像这样:[{conversation_id: String, userOne: Object, userTwo: Object
}]
不过我不确定是否可行。
首先,在 mongoose 中内置了填充逻辑,这意味着您应该能够添加如下内容:
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: 1, name: 'Hello', otherTableId: 2}];
现在我希望遍历所有这些数组并从我的 MongoDB 中获取一些数据,我想将这些数据附加到一个新数组,然后 returned.
我如何使用 q
执行此操作?
这是我到目前为止的内容,但我不知道用什么来替换 foreach
:
router.route('/api/conversations')
.get(function (req, res) {
mongoose.models.conversation.find({users: {$all: [req.query.id]}}, function (err, conversation) {
if (err) {
res.status(500).send(err)
}
else {
var returnArray =[];
conversation.forEach(function (x) {
})
}
});
});
我的架构
var conversation = mongoose.Schema({
users: Array
});
var user = mongoose.Schema({
username: String,
password: String,
firstname: String,
lastname: String,
is_active: Boolean,
user_type: Number
});
我想要的 return 基本上是对话及其用户的列表。
像这样:[{conversation_id: String, userOne: Object, userTwo: Object
}]
不过我不确定是否可行。
首先,在 mongoose 中内置了填充逻辑,这意味着您应该能够添加如下内容:
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
})