【问题标题】:Find and update of object in nested array查找和更新嵌套数组中的对象
【发布时间】:2019-04-13 07:57:41
【问题描述】:

我有这个猫鼬模式

{
    id: mongoose.Schema.Types.ObjectId,
    name: String,
    initialMailSended: Boolean,
    email: String,
    users: [{
        id: mongoose.Schema.Types.ObjectId,
        name: String,
        surname: String,
        email: String,
        signedUp: Boolean,
        company: String,
        email: String,
        attending: String,
        accomod: String,
        program: String,
        food: String,
        other: String,
        allFood: String,
        form: [{
            name: String,
            value: String,
        }]
    }]
}

我需要做的是编写一个猫鼬查询,它通过 id 找到这个对象,并在这个对象中找到用户并更新它。 我尝试了各种查询,但没有找到任何可行的方法。

【问题讨论】:

标签: mongodb mongoose mongodb-query


【解决方案1】:

对于您的问题,您可以像这样更新您的用户

db.getCollection('collection').findOneAndUpdate(
    {
      _id:ObjectId("5cb19dbc85fdcb7868400107"),       // collection id
     'users._id':ObjectId("5cb19dbc85fdcb7868400185") // user id inside collection
    },

    {$set: {'users.$.name': 'new value'}}            // set name field
)

也看到这个问题Updating a Nested Array with MongoDB

【讨论】:

  • Actions.find({ _id: actionId, 'users._id': userId }, (err, data) => { //console.log(data[0].users); console.log('data', data); }) 这个解决方案返回数组中所有对象的数据
  • 已解决 - 问题是在解决方案的 $set 部分中使用固定值而不是 $
猜你喜欢
  • 2017-04-04
  • 1970-01-01
  • 2018-09-10
  • 2023-03-26
  • 1970-01-01
  • 2019-08-03
  • 2023-04-03
  • 2016-07-27
  • 2019-11-02
相关资源
最近更新 更多