问题
I am developing using express js and npm module mongodb with mongodb as database. I have two collections namely "users" and "activities". There can be 1000s of activities of a User.
Firstly I am storing id, name and picture url of the user into the activity document for relation. Please tell me if this is wrong for relations and suggest something for storing the relation.
Secondly the problem I am facing now is when I update a user's name it doesn't get updated in the activities of the user (which is
obvious). I want some example so that I can update many docs at once using the user id.
Please help on the above. Thanks in advance.
回答1:
- This is typical one-to-many relationship. So in case of the User you can have the following schema:
//User
{
//_id: ObjectId - this one is unique and inserted to every document by default
profile: String,
...
}
//Activity
{
description: String,
...,
userId: String, // referecing the user _id, e.g. "56a5eccb2258799919dc2c40"
}
- If you want to update many docs for activity:
db.activities.update({ userId: '56a5eccb2258799919dc2c40' }, {
$set: {
description: 'new description'
}
},
{
multi: true //means update all matching docs
});
回答2:
You should store just the _id of the User in the Activity. Then use that to access the User via the Activity (if that's what you want to do).
来源:https://stackoverflow.com/questions/35037566/mongodb-update-many