【问题标题】:update single item within array where multiple conditions apply to any array item更新数组中的单个项目,其中多个条件适用于任何数组项目
【发布时间】:2017-09-12 11:49:05
【问题描述】:

我有一个基本的猫鼬模型,其属性instruments 表示一个数组。因此它包含多个项目,每个项目具有以下属性:namecounter。文档本身有一个自动生成的_id,类型为ObjectID

型号

var ParticipationSchema = new Schema({
    instruments: [{
      name: String,
      counter: Number
    }],
// etc.
},
{
    timestamps: true
});

我现在想准确更改 instruments 数组中的一项,前提是它符合以下要求:

  1. 文档ID必须等于58f3c77d789330486ccadf40
  2. 应该更改的instruments-item 的name 必须等于'instrument-1'
  3. instrument-item 的counter 必须低于3

查询

let someId = '58f3c77d789330486ccadf40';
let instrumentName = 'instrument-1'
let counter = 3;

Participation.update(
{
    $and: [          
      { _id: mongoose.Types.ObjectId(someId) },
      { 'instruments.name': instrumentName },
      { 'instruments.counter': { $lt: counter } }
    ]},
    {
      $set: {
        'instruments.$.currentcounter' : counter
      }
    },
    (err, raw) => {
      // ERROR HANDLING
    }
});

假设我在 instruments-attribute 中有 3 个条目:

"instruments": [
  {
    "name": "instrument-1",
    "counter": 2
  },
  {
    "name": "instrument-1",
    "counter": 2
  },
  {
    "name": "instrument-1",
    "counter": 2
  }
]

期望的行为:将第一个元素的counter属性更改为3,无论如何,运行更新代码1次时,运行多次时不执行任何操作。

实际行为:

  • 它在第一次运行时将第一个元素的 counter 属性更改为 3
  • 它在第二次运行时将 2nds 元素的 counter 属性更改为 3
  • 它在第三次运行时将 3rds 元素的 counter 属性更改为 3

【问题讨论】:

    标签: arrays mongodb mongoose mongoose-schema


    【解决方案1】:

    虽然查询是anded,但它们似乎并没有按元素运行。要解决此问题,可以使用$elemMatch

    Participation.update({
             _id: mongoose.Types.ObjectId(someId),
             'instruments': {
                $elemMatch: {
                  'name': instrumentName,
                  'counter': { $lt: counter } }}
          },
          // etc.
    

    更多信息:

    【讨论】:

    猜你喜欢
    • 2019-01-27
    • 2021-03-20
    • 2011-04-25
    • 2019-02-10
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多