我有一个动态保存文档id的数组,在这个数组中,我需要在mongo中查询另一个排序规则,以查看id是否匹配。我有这样的代码:
let collection = database.collection('login')
let doc = await collection.find({ email: req.session.username }).toArray()
let array_of_docs_bought = []
for (var i = 0; i < doc.length; i++) {
array_of_docs_bought.push(doc[i].list_of_docs_bought)
}
let documents = await database.collection('documents').find({ "id": { $in: array_of_docs_bought } }).toArray()但是,执行"id": { $in: array_of_docs_bought }不会迭代数组,因此它不会返回任何内容,但是当我这样做时:
let documents = await database.collection('documents').find({ "id": { $in: [ 'g81h8', '2ac3c', 'juc8d', 'g81h8', 'h9k2c' ] } }).toArray()
它可以工作,因为数组的值是存在的,而且它们不是任何需要迭代的东西。那么,如果更有意义的话,我如何使它在array_of_docs_bought中迭代,或者重新格式化所有的代码。
发布于 2022-11-05 20:19:49
array_of_docs_bought.push(doc[i].list_of_docs_bought)似乎是这里的罪魁祸首。根据数据的形状,您可能会将数组推到数组中,使用嵌套数组结束。这将通过“扩展操作符”进行修复:
let array_of_docs_bought = []
for (var i = 0; i < doc.length; i++) {
array_of_docs_bought.push(...doc[i].list_of_docs_bought)
}https://stackoverflow.com/questions/74331142
复制相似问题