不能用mongoose将项目推送到数组中

时间:2021-09-12 02:36:29

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

我正在尝试使用POST请求将项添加到用户对象中的集合中。

  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":"lilly@test.com","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}

{“name”:“MongoError”,“message”:“exception:'$ push'为空。您必须指定如下字段:{$ push:{:...}}”,“value”:{“ _id “:” 5546cc0483b0186428e252cc”, “电子邮件”: “lilly@test.com”, “passwordHash”: “Q + VpK9L + I / DhAm7w01AArMacBkXEdyHp3zGF6JyJVzDhwgHpws4z8IBxycI7xrRX6Do2AEe / BvI37HauvAc6WA ==”, “盐”: “0Bi6XW0YuxutizQY3PZH4Q ==”, “预算” :5000,“shopping_list”:[],“橱柜”:[],“饭”:[],“__ v”:0},“errmsg”:“例外:'$ push'为空。你必须指定一个字段像这样:{$ 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...

我不明白为什么会发生这种情况,因为字段'shopping_list'清晰可见并且值传递...

Anybody know what I'm doing wrong??

谁知道我做错了什么?

1 个解决方案

#1


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

默认情况下,Mongoose不会更新未出现在模型架构中的字段。

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

因此,要么将shopping_list添加到架构中,要么将架构上的strict选项设置为false。

#1


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

默认情况下,Mongoose不会更新未出现在模型架构中的字段。

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

因此,要么将shopping_list添加到架构中,要么将架构上的strict选项设置为false。