2

I'm trying to use a POST request to add an item into a collection within a user object.

  User.findOneAndUpdate(
    {"_id": req.body.userid}, 
    {$push: {'shopping_list': req.body.itemid}},
    {safe: true, upsert: true},
    function(err, Model){
      console.log(err, Model);
      if(err){
        handleError(res, err);
      }
      return res.status(201).json(Model);
    }
  );

I keep getting the following error:

{"name":"MongoError","message":"exception: '$push' is empty. You must specify a field like so: {$push: {: ...}}","value":{"_id":"5546cc0483b0186428e252cc","email":"[email protected]","passwordHash":"Q+VpK9L+I/DhAm7w01AArMacBkXEdyHp3zGF6JyJVzDhwgHpws4z8IBxycI7xrRX6Do2AEe/BvI37HauvAc6WA==","salt":"0Bi6XW0YuxutizQY3PZH4Q==","budget":5000,"shopping_list":[],"cupboard":[],"meals":[],"__v":0},"errmsg":"exception: '$push' is empty. You must specify a field like so: {$push: {: ...}}","code":9,"ok":0}

I can't see why that's happening as the field 'shopping_list' is clearly visible and a value is passed...

Anybody know what I'm doing wrong??

2
  • Is shopping_list in the schema definition for User? Commented May 5, 2015 at 1:03
  • shame mode I commented it out whilst fixing another bug... :D If you add it as the answer, I'll accept it... Thanks @JohnnyHK. Commented May 5, 2015 at 1:18

1 Answer 1

13

By default, Mongoose won't update fields that do not appear in your model's schema.

So either add shopping_list to your schema or set the strict option on the schema to false.

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

1 Comment

This gave me a really good idea what the problem was in my case. Thanks

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.