I am updating a Group document with multiple Role subdocuments , but the returned value is not the updated group :
The group is updated correctly:
Mongoose: groups.update({ _id: ObjectId("592e823e61229c36f3436e06") }, { '$push': { roles: {
'$each': [ { _id: ObjectId("592e823f61229c36f3436e0c"), description: 'Description Role0', name:
'Role0' }, { _id: ObjectId("592e823f61229c36f3436e0b"), description: 'Description Role1', name:
'Role1' }, { _id: ObjectId("592e823f61229c36f3436e0a"), description: 'Description Role2', name:
'Role2' }, { _id: ObjectId("592e823f61229c36f3436e09"), description: 'Description Role3', name:
'Role3' } ] } }, '$setOnInsert': { __v: 0 } }, { upsert: true })
Displaying the updated group in the console , Iget :
UPDATED GROUP WITH ROLES: {"n":1,"nModified":1,"ok":1}
with this code:
addMultipleRoles(groupId, n) {
const multiRoles = [];
for (let i = 0; i < n; i += 1) {
multiRoles.push({ groupId: groupId, name: `Role${i}`, description: `Description Role${i}` });
}
return Group.update({_id: groupId}, {$push: {roles: {$each: multiRoles}}}, {upsert:true} )
.then((savedGroup) => {
console.log('UPDATED GROUP WITH ROLES: %j', savedGroup);
return savedGroup;
})
.catch((e) => {
if (e.name === 'ValidationError' && e.errors.name.kind === 'unique') {
console.log( 'Existing role(s)');
} else {
console.log('error saving multi roles %j', e);
}
return [];
});
},
That's what MongoDB's update
does: it updates the document in the database and returns a so-called WriteResult
.
If you want to retrieve the updated document, you can use findOneAndUpdate
combined with the new
option:
Group.findOneAndUpdate({
_id : groupId
}, {
$push : { roles : { $each : multiRoles } }
}, {
upsert : true,
new : true
}).then(...)