[英]Mongodb many to many relation issue
I have a small issue here to dynamically retrieve documents and update them. 我在这里有一个小问题,可以动态检索文档并更新它们。 I have a many-to-many relation between 2 documents: House with an userid and my User collection. 我在2个文档之间存在多对多关系:带用户ID的房屋和我的用户集合。 What I want to do is: save an User document found with the idUser from the House document, to the House document 我想做的是:将与House的idUser一起找到的User文档保存到House的文档中
My house document looks like this: 我的房屋文件如下所示:
House: 屋:
{
"id": 1
"idUser": 3
}
and my User document: 和我的用户文档:
{
"id": 3
"name" : Test
"lastname": TEST
}
and I want the following result: 我想要以下结果:
House: 屋:
{
"id":1
"idUser":3
"user": { "name": Test, "lastname": TEST } // document fetched from the House's idUser
Here is an example of my code: 这是我的代码示例:
house.find().done(function(err,h){
for(var i = 0 ; i < h.length ; i++){
User.findOne({ id: h.idUser}).done(function(err,user){
h[i].user = user; // issue here is that the variable 'i' is not defined anymore after it enters in the "done" function
}
console.log(h);
}
});
Would be thankful to anyone who has a clue about it. 会对任何对此有所了解的人表示感谢。 Best regards, 最好的祝福,
Your problem is the async function call within your for-loop. 您的问题是for循环中的异步函数调用。 This cannot work because, when the callback is is called the first time, the loop is done and i
equals h.length
. 这是行不通的,因为在第一次调用回调时,循环已经完成,并且i
等于h.length
。
You have to do it this way: 您必须这样做:
house.find().done( function( err, h ) {
function processHouse( i, callback ) {
if( i < h.length ) {
console.log( "House: " + i );
User.findOne({ id: h.idUser}).done( function( err, user ){
h[i].user = user; // issue here is that the variable 'i' is not defined anymore after it enters in the "done" function
processHouse( i+1, callback );
});
} else {
callback()
}
}
processHouse( 0, function() {
console.log( "Done!" );
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.