【问题标题】:Mongoose update the ENTIRE object inside a document with a nested arrayMongoose 使用嵌套数组更新文档中的整个对象
【发布时间】:2020-07-22 15:28:40
【问题描述】:

关于这个主题有很多问题和答案,但为什么不把它简单化。

分支架构

const Branch = new Schema({
    name:    { Type: String },
    address: {
                 houseNumber: { Type: String },
                 street:      { Type: String },
                 city:        { Type: String }
             }
})

客户端架构

const Client = new Schema({
    ...,
    ...,
    branches: [ branch ] // BRANCH SCHEMA IS SUB DOCUMENTED HERE
})

我知道如何从branches 数组中分支$push$pull
我需要的是更新分支数组内的ENTIRE分支对象,不只是一个字段,就像我在很多答案和中找到的那样是的 我想取回修改后的文档。

let clientId = req.body.clientId;
let branch   = req.body.branch;

Client
.findOneAndUpdate(
    { 
        "_id": clientId,
        "branches._id": branch._id
    },
    {
        OPTION 1 // MODIFIED ONLY THE FIRST ITEM (object) IN THE ARRAY
        "$set:" { "branches.$": { branch } }

        OPTION 2 // MODIFIED EVERY ITEM (object) IN THE ARRAY
        "$set:" { "branches.$[]": { branch } }
        
        STILL NO GOOD... HOW TO SOLVE THIS ??        
                                
    }
)
.then(client => {
    
    WHAT SHOULD I DO HERE IN ORDER TO UPDATE AN ENTIRE BRANCH ??

})
.catch(e => console.log(`error Client.findOne() ${e}`))

【问题讨论】:

  • 这能回答你的问题吗? Replacing embedded document in array in MongoDB
  • 否,在提供的链接中有 2 个示例,第一个示例始终修改数组中的第一个对象,如果我将 "branches.$" 更改为 branches.$[],它会修改数组中的所有对象。第二个例子对我的情况没有好处。谢谢@Jiří
  • 第一个示例并不总是修改第一个对象,它修改了该数组中的第一个 匹配 对象。看看documentation
  • @Jiří,我用您提供的链接中的示例更新了我的问题,那么我的错误在哪里?

标签: mongodb mongoose


【解决方案1】:

你可以使用猫鼬arrayFilters来实现你想要的:

Client
.findOneAndUpdate(
    { 
        "_id": clientId,
        "branches._id": branch._id
    },
    {
        "$set:" { "branches.$[elem]": { branch } }                                
    },
    {
        arrayFilters: [ { 'elem._id': branch._id } ]
    }
)
.then(client => {

})
.catch(e => console.log('error Client.findOne() + e))

【讨论】:

  • 不,这也会更新数组中的每个元素,感谢您尝试@Mahan。
【解决方案2】:

好的,我就是这样做的..

let clientId = req.body.clientId;
let branch   = req.body.branch;

Client
.findOne({ _id: clientId })
.then(client => {
         
      // finding the index
      const elementIndex = client.branches.findIndex(element => element._id.toString() === branch._id.toString());

      // creating new array and assigning the branches array to it using spread syntax 
      let newBranches = [ ...client.branches ];

      // adding the branch I need to update to newBranches array (at the same index)
      newBranches[elementIndex] = branch;

      // replacing branches array with the new one, again using spread syntax
      client.branches = [ ...newBranches ];

      // saving
      client.save();
})
.catch(e => console.log(`error Client.findOne() ${e}`))

享受吧!

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    相关资源
    最近更新 更多