Reputation: 807
I'm trying to add object id to array in mongoose (Node.js). Here is my code:
app.post('/api/users/:userId/favorites/:objectId', function(req, res, next) {
User.findByIdAndUpdate(req.params.userId, {$addToSet: {user_favorites: req.params.objectId}}, {safe: true, upsert: true}, function(err, data){
if (err) return res.status(500).send(err)
res.status(200).send({'message':'saved'});
})
})
And here is my model:
module.exports = mongoose.model('User',{
...
user_favorites: [{ type: mongoose.Types.ObjectId, ref: 'Property' }],
...
})
No errors are returned but the id is not added to the array. What am I missing?
Upvotes: 1
Views: 426
Reputation: 50406
You forgot the "new" option. The .find**Update()
methods have this turned off by default, which is the same behavior as the root method .findAndModfiy()
:
User.findByIdAndUpdate(
req.params.userId,
{ "$addToSet": {
"user_favorites": req.params.objectId
},
{ "upsert": true, "new": true },
function(err, data){
if (err) return res.status(500).send(err)
res.status(200).send({'message':'saved'});
}
)
So the document is actually updated in the database, but without "new" then you get the original document found, and not the modified one.
Also, whatever tutorial you learnt from, the "safe" option has been deprecated for a very long time. All write concern setting default to acknowleded, which is what that setting is supposed to represent.
Upvotes: 1