【问题标题】:updating an array in mongodb更新 mongodb 中的数组
【发布时间】:2018-03-14 08:57:37
【问题描述】:

对于以下结构,我正在尝试将选项下的第一个数组项更新为 ["milk", 1]:

{    
  options:[["milk", 0],
           ["chocolate", 0],
           ["others", 0]],
  timestamp:"2017-09-26T14:42:49.359Z"
  title:"shopping list"
  username:"a"
}

这是我使用的 mongoose sn-p。

router.put('/',(req,res) => {
  let {_id, value, option} = req.body;   
  eventModel.findOneAndUpdate(    
    {_id:_id, options: [option, value]},
    { $set: {"options.$": [option, value + 1]}},
      function(err){
      if(err){
          res.status(400).json({ error: err });
      }
      console.log("event updated");
  });    
});

我总是得到没有错误的“事件更新”,但项目没有得到更新,感谢任何帮助。谢谢

【问题讨论】:

标签: javascript arrays node.js mongodb mongoose


【解决方案1】:

你为什么使用这种数组对来存储你的值? 任何具体原因。

否则你可以这样存储数据,然后查询:

const ShoppingListSchema = new Schema({
  username: {type: String},
  title: {type: String},
  timestamp: {type: Date, default: Date.now()},
  options: [{
    product: {type: String},
    selected: {type: Number}
  }]
});
  // then
  eventModel.findOneAndUpdate(    
    {_id:_id, 'options.product': productName, 'options.selected': selected},
    {"options.$.value": value + 1},
      function(err){
      if(err){
          res.status(400).json({ error: err });
      }
      console.log("event updated");
  }); 

// 同样,快速注释。如果您想将列表中的项目设置为“包含”或不设置,那么……您实际上并不需要“价值”部分。 产品在购物清单中,如果它在数组中。

options: ["milk", "bread", "beer"] would work just as well

另外,我可以看到你在做“价值 + 1” 快速说明一下,有一个用于递增值的操作数:

$inc: {field: value}

使用替代选项快速更新:

db.getCollection('list').update({"options": ["milk", 0]}, {$set: {"options.$.1": 1} })

use $.1 to refer to the second element in your array, which is the number.

【讨论】:

  • 感谢@的回答。老实说,整个架构并不是最优的,但如果我在这一点上改变它,我需要做很多重构。所以我想知道是否有办法按原样更新数据。
  • 只是想标记@user:1932379
猜你喜欢
  • 2015-08-27
  • 2016-02-09
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
相关资源
最近更新 更多