user1775718
user1775718

Reputation: 1578

Cannot $push item into array with mongoose

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??

Upvotes: 2

Views: 3542

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312115

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.

Upvotes: 13

Related Questions