node.js - 如何对mongodb两个集合和集合内嵌套数组对象进行update更改?
怪我咯
怪我咯 2017-04-17 16:28:48
0
3
406
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
刘奇

Isn’t it better to seek help from others than to seek help from yourself? Finally solved it Posted it for everyone’s reference

mongodb.open(function(err, db) {
        if (err) {
            return callback(err);
        }
        db.collection('users', function (err, collection) {
            if (err) {
                mongodb.close();
                callback(err);
            }
            db.collection('posts', function (err, collectionofposts) {
                if (err) {
                    mongodb.close();
                    callback(err);
                }
            collection.update({"name": name}, {$set: {"head": head}}, function(err) {
                if (err) {
                    return callback(err);
                }
                collectionofposts.update({"name": name}, {$set: {"head": head}}, {multi: true}, function(err) {  
                    if(err) {
                        return callback(err);
                    }
                    collectionofposts.find().forEach( function(doc) {
                        collectionofposts.update({_id: doc._id, "comments.name": name},
                                        {$set: {"comments.$.head": head}}, {multi: true});
                        }, function(err) {
                            if(err) {
                                return callback(err);
                                }
                            mongodb.close();
                            callback(null);
                        });
                    });
                });
            });
        });
    });
}
巴扎黑

What you mean is that if the user changes his avatar, he needs to change the user’s avatar in the post as well

The model you mentioned above does not feel suitable for this scenario; it is better to save the user ID in the post and the user ID in the comments, so that you don’t need to change the information of one user, and you need to modify the corresponding information in multiple places, of course. This method requires you to obtain user information when querying comments information, for example, and you need to make your own choices

If updated,

db.posts.update({userId:'xxxxxx'},{$set:{"head" : "/images/portrait-1490968786371.jpg"}})//Similar to this

阿神

Mongodb is not a relational database. It cannot be done with a single SQL statement. It can only be done with nested queries. For people who are used to using relational databases, it is simply impossible to see directly. And seeing that bunch of if (err) { mongodb.close(); callback(err);} makes me even more crazy

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template