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?
ObjectId.var id = mongoose.Types.ObjectId(req.params.objectId);. You'll want to verify the format of the user input as well, it must be a single String of 12 bytes or a string of 24 hex characters. That or catch the Error.