[英]Get json array from sub mongoose query
我在貓鼬中有一個子查詢,需要從子查詢中獲取數組並將其附加到主json的put /對象中。 我的第一個查詢獲取的用戶信息包含blocked_users數組,該數組不過是用戶ID的數組。
在第二個查詢中,我們獲取blocker_users數組的配置文件詳細信息,並附加到blocked_users中的主要用戶對象。
var userId = ObjectID(req.body.user_id);
//Get user
newUserModel.findById(userId, function(err, user){
if(err){
utils.getResponse(res, req.url, messages.failure, "");
} else {
var userInfo = {};
var blcked_contacts;
//get users details from blocked contacts userid's array
newUserModel.find({'_id': {$in:user.blocked_contacts}}, function (err,blocked_users) {
if(blocked_users){
//blcked_contacts.push(blocked_users);
console.log(blocked_users);
return;
};
/*else{
blcked_contacts = [];
}*/
});
userInfo['blocked_contacts'].push(blocked_users);
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
//userInfo['blocked_contacts'].push(blcked_contacts);
//userInfo['blocked_contacts'] = user.blocked_contacts;
var userData = Array();
}
});
真的不知道您要尋找什么。 但是在您的代碼中看到了一個問題。 您已將block_users分配給find方法之外的blocked_contacts字段。
由於這些調用本質上是異步的,因此可能甚至在從MongoDB提取文檔之前進行分配。 因此,您應該像Medet一樣,在find方法的回調中編寫賦值語句。
在代碼中發現了一些錯誤,例如嘗試在對象上使用.push 。 你不能做
userInfo['blocked_contacts'].push(blocked_users); // incorrect as userInfo is an empty object and you dont have an array defined for userInfo['blocked_contacts']
您可能無法為此輸入未定義的錯誤。 所以做
userInfo['blocked_contacts'] = blocked_users;
另外,您還必須在第二個find()內部執行此操作,因為blocked_users僅在其中可用。 因此,您的最終查詢應類似於
var userId = ObjectID(req.body.user_id);
//Get user
newUserModel.findById(userId, function(err, user){
if(err){
utils.getResponse(res, req.url, messages.failure, "");
} else {
var userInfo = {};
//get users details from blocked contacts userid's array
newUserModel.find({'_id': {$in:user.blocked_contacts}}, function (err,blocked_users) {
if(blocked_users){
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
userInfo['blocked_contacts'] = blocked_users; // assign blocked_users into userInfo
console.log(userInfo) // Your required object
} else {
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
userInfo['blocked_contacts'] = []; // assign null array if no blocked users fould
}
});
var userData = Array();
}
});
console.log的結果應該是這樣的對象
{
user_id : "..id of searched user...",
country_code : "..country code of searched user..",
blocked_contacts : [<array containing detais of all blocked users>] // null array if no users found
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.