猫鼬使用嵌套数组更新文档内部的ENTIRE对象

时间:2020-07-21 07:22:27

标签: mongodb mongoose

关于这个主题有很多问题和答案,但是为什么不简单一点。

分支架构

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
})

我知道如何$push$pullbranches数组分支。
我需要的是更新分支数组内的整个分支对象,不只是一个字段,就像我在很多答案中发现的那样,,我想退回修改后的文档。

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}`))

2 个答案:

答案 0 :(得分:0)

您可以使用猫鼬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))

答案 1 :(得分:0)

好的,这就是我的做法。

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}`))

享受!