gpt4 book ai didi

node.js - 如何在 Mongoose 中将一个查询的对象用于嵌套查询

转载 作者:太空宇宙 更新时间:2023-11-03 23:29:17 25 4
gpt4 key购买 nike

我是 MongoDb 和 NodeJs 的新手,我在 NodeJS 中使用 Mongoose,但我面临一个问题,我将第一个查询的结果对象使用到嵌套查询中,但第一个查询对象未定义。请给我任何建议。谢谢。

LuckyLunch.find(criteria, function (err, lunches) {   // First Query
if (err)
return;
var allLunches = lunches; // Accurate result here
for (var i = 0; i < allLunches.length; i++)
{
if (typeof allLunches[i].luckyMatch != 'undefined') {
var usernames = [];
Match.findOne(criteria2, function (err, singleMatch) { // Second Query
if (singleMatch != null) {
var userids = [];
for (var k = 0; k < singleMatch.participants.length; k++)
{
userids.push(ObjectId(singleMatch.participants[k]));
}
User.find(criteria, function (err, getusers) { // Third Query
for (var j = 0; j < getusers.length; j++)
usernames.push(getusers[j].name);

allLunches[i].luckyUsers = usernames; // allLunches[i] is undefined here.

});
}
});
}
}
});

最佳答案

试试这个,

 var getData = function(callback) {
LuckyLunch.find(criteria, function (err, lunches) { // First Query
if (err) {
callback(err);
return;
}
var len = lunches.length; // try to use lenches only, Accurate result here
for (var i = 0; i < len; i++)
{
(function(i) {
if (typeof lunches[i].luckyMatch != 'undefined') {
var usernames = [];
Match.findOne(criteria2, function (err, singleMatch) { // Second Query
if (singleMatch) {
var userids = [];
for (var k = 0; k < singleMatch.participants.length; k++)
{
userids.push(ObjectId(singleMatch.participants[k]));
}
User.find(criteria, function (err, getusers) { // Third Query
for (var j = 0; j < getusers.length; j++)
usernames.push(getusers[j].name);

lunches[i].luckyUsers = usernames; // allLunches[i] is undefined here.

});
}
});
}
})(i);
}

callback(null, "put here need data to return"); //this must be end of the ur loop
});

}

getData(function(err, result){

if(err)
console.log(err);
else
console.log(result);
});

关于node.js - 如何在 Mongoose 中将一个查询的对象用于嵌套查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40145765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com