怪我咯2017-04-17 16:30:48
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);
});
});
});
});
});
});
}
巴扎黑2017-04-17 16:30:48
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
阿神2017-04-17 16:30:48
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