繁体   English   中英

Mongodb多对多关系问题

[英]Mongodb many to many relation issue

我在这里有一个小问题,可以动态检索文档并更新它们。 我在2个文档之间存在多对多关系:带用户ID的房屋和我的用户集合。 我想做的是:将与House的idUser一起找到的User文档保存到House的文档中

我的房屋文件如下所示:

屋:

{ 
"id": 1
"idUser": 3
}

和我的用户文档:

{
"id": 3
"name" : Test
"lastname": TEST
}

我想要以下结果:

屋:

{
"id":1
"idUser":3
"user": { "name": Test, "lastname": TEST }   // document fetched from the House's idUser

这是我的代码示例:

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);   

    }

});

会对任何对此有所了解的人表示感谢。 最好的祝福,

您的问题是for循环中的异步函数调用。 这是行不通的,因为在第一次调用回调时,循环已经完成,并且i等于h.length

您必须这样做:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM