【问题标题】:How to push a new value to a nested array in Mongoose如何将新值推送到 Mongoose 中的嵌套数组
【发布时间】:2019-11-19 14:55:00
【问题描述】:

我正在使用猫鼬。如何将新值推送到数组fixture2

这是我的收藏。我使用userHash 来识别此文档。

{
    "_id" : ObjectId("5d2548beb1696f1a2d87d647"),
    "userHash" : "5c4b52fc2dfce2489c932e8fcd636a10",
    "fixtures" : [ 
        {
            "fixture1" : [ 
                "vote1", 
                "vote2"
            ],
            "fixture2" : [ 
                "vote1", 
                "vote2", 
                "vote3"
            ],
            "fixture3" : [ 
                "vote1"
            ]
        }
    ],
    "__v" : 0
}

fixtures 可以有任意数量的元素。在这种情况下,它只有 3 个。

这是我的模型。

var mongoose = require( 'mongoose' );
var votesSchema = mongoose.Schema({
  userHash: String, 
  fixtures: [{}]
});
module.exports = mongoose.model('votes', votesSchema);

但是,我正在努力尝试将值 vote4 推送到 fixture2。是否可以使用findOneAndUpdate 提交?

【问题讨论】:

  • 要推送到fixtures数组的所有元素的fixture2吗?

标签: arrays mongodb mongoose push


【解决方案1】:

您可以使用$push 来执行此操作。

例子:

YourModel.findOneAndUpdate(condition, {$push: {"fixtures.0.fixture2": "vote4"}})

【讨论】:

    【解决方案2】:

    您可以使用以下查询

    update(
      { "fixtures.fixture2": { "$exists": true } },
      { "$push": { "fixtures.$.fixture2": "vote4" } }
    )
    

    【讨论】:

      【解决方案3】:

      您可以使用$(update) 位置运算符来实现这一点。

      另外,不要忘记在您的更新选项中使用{multi : true},以更新您收藏中的所有documents

      试试这个:

      Votes.update(
        { "fixtures.fixture2": { "$exists": true } },
        { "$push": { "fixtures.$.fixture2": "vote4" } },
        { multi : true}
      )
      

      但这只会更新第一个匹配的fixture2。

      要更新 fixtures 数组中所有元素的 fixture2,您可能需要改用 $[]

      试试这个:

      Votes.update(
        { "fixtures.fixture2": { "$exists": true } },
        { "$push": { "fixtures.$[].fixture2": "vote4" } },
        { multi : true}
      )
      

      阅读更多关于$[](positional-all)的详细信息。

      【讨论】:

      • 感谢您的回答...实际上,这是我正在测试的最后一个查询,因为我需要检查哪些用户正在投票...``` votes.findOneAndUpdate( {userHash: hash , 'fixtures.fixture3': {$exists: true}}, {$push: { "fixtures.$.fixture3": 'vote11'}}) ``` 但是,它只有在 fixtures.fixture3 数组存在时才有效。我想我需要进行一些先前的验证以验证数组是否存在......如果不存在,我需要在尝试推送一些数据之前创建它。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2019-03-28
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      相关资源
      最近更新 更多