Reputation: 1839
I want to update some properties of a Sub-Document. My Models and update function are looking like the following:
const ParentSchema = mongoose.Schema({
...
subs : [SubSchema],
...
})
const SubSchema = mongoose.Schema({
...
name : String,
price : Number,
...
})
const ParentModel = mongoose.model('Item', ItemSchema);
function updateSubDocument(parentId, subId, updateObj){
return ParentModel.update(
{'_id' : parentId, 'subs._id' : subId},
{
'$set' : {
'subs.$' : updateObj
}
},
{
new : false,
overwrite : true,
runValidators: true
}
).exec();
}
Now when I'm trying to update some properties of specific Sub-Documents, mongoose does 2 strange things:
The properties of the Sub-Document are getting overwritten by the updateObj, so all other properties (which are not in the updateObj) are missing.
I cant update the overwritten Sub-Document after the first a second time, the values are not changing
ubuntu : 16.04, mongoose : 5.1.3, nodejs : 8.11.1,
Upvotes: 1
Views: 1174
Reputation: 66
https://docs.mongodb.com/manual/reference/operator/update/positional/
Try Updating with the following query:
function updateSubDocument(parentId, subId, updateObj){
return ParentModel.update(
{'_id' : parentId, 'subs' : {$elemMatch:{_id:subId}},
{
'$set' : {
'subs.$.name' : updateObj.name,
'subs.$.price' : updateObj.price,
......
}
},
{
new : false,
overwrite : true,
runValidators: true
}
).exec();
}
Upvotes: 2