1

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?

1
  • You are also adding a string to the array/set. You need to convert it to an 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. Commented Jul 26, 2015 at 12:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, you are right. All the favorites were saved. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.