I have a mongo schema as below
var schema = mongoose.Schema({
user: {type:ObjectId, ref: 'User'},
preferences: mongoose.Schema.Types.Mixed
});
module.exports = mongoose.model('UserPreference', schema);
I'm making a post call with data
{
"newQuestionPrompt": false,
"oldQuestion": false
}
Each of these properties need to get set into the preferences field, for example
"_id" : ObjectId("58f9d06cf998d9baccf8024f"),
"user" : ObjectId("58eda68601dc391e27f3e2c4"),
"preferences":{
"newQuestionPrompt": false,
"oldQuestion": false
}
However, when the same post call is made for the same user again, there might be entirely different properties in the call, or the same properties with different values, like
{
"newQuestionPrompt": true,
"randomQuestion": false
}
In this case, I need to update the values of properties which already exist and add the ones which aren't, so the earlier object should become
"_id" : ObjectId("58f9d06cf998d9baccf8024f"),
"user" : ObjectId("58eda68601dc391e27f3e2c4"),
"preferences":{
"newQuestionPrompt": true,
"oldQuestion": false,
"randomQuestion": false
}
I can't use $set preferences:req.body as it would overwrite the whole thing. What would be the best way to accomplish this?
via Karthik
No comments:
Post a Comment