简体   繁体   English

如何在使用Mongoose中更新嵌套对象

[英]How to update a nested object in using Mongoose

Let say the current data on a given User is 假设给定User的当前数据为

{
            accountType:12,
            address:{
                address1:"uk1"
            },
            shareDealing:{
                providers:{
                    uk:{
                        accountProviderId:"12",
                        accountProviderName: "as",
                    }
                }
            }
        }

Then I want to insert the following data changing all fields except that I am not including the shareDealing.providers.uk.accountProviderName because it hasn't changed and i expect that one to remain on the User's document 然后,我想插入以下数据来更改所有字段,但我不包括shareDealing.providers.uk.accountProviderName因为它没有更改,并且我希望保留在用户文档中

So my data to update would be 所以我要更新的数据是

user = {
            accountType:22,
            address:{
                address1:"aaaaaa"
            },
            shareDealing:{
                providers:{
                    uk:{
                        accountProviderId:"333333333333",
                    }
                }
            }
        };

So I ran the following code 所以我运行了以下代码

User.update(searchBy, user, {upsert:true}).then((data) =>{

            if(data === null) throw new AppError(400,"User Not Found",5);

            res.json({ message: 'User Updated', data: req.body });
            logger.debug("Saved Data : Using  "+ JSON.stringify(searchBy) +" record: "+ JSON.stringify (data));
        }).catch( (error) => {
            new Errorhandler( new AppError(400,error)).display(req,res);
        });

My problem 我的问题

When I do the update the updated User's record doesn't have the accountProviderName: "as" as it think that the latest JSON should be the full User record. 当我进行更新时,更新的用户记录没有accountProviderName: "as"因为它认为最新的JSON应该是完整的用户记录。

Is there a way to update all changed fields but keeping the previous non-touched fields with just an update? 有没有一种方法可以更新所有更改的字段,但仅通过更新保留以前的非接触字段?

I know a workaround is using the following code but (maybe wishful thinking) I would prefer to validate and assign data to my User record outside my update function chain. 我知道一种解决方法正在使用以下代码,但是(也许是一厢情愿),我希望在更新功能链之外验证数据并将其分配给我的用户记录。

It feels overkill having to do 2 calls to the DB one to find and another to update 不得不两次对数据库进行一次调用来查找,而另一个要进行更新,这感觉有点过头了

User.findById(searchBy).then((fetchedUser) => {
            if(fetchedUser === null) throw new AppError(400,"User Not Found",5);

            // In my ideal world i would prefer to validate and assign data outside this chain
            return functionThatValidatesAndAssignsDataToTheUser(fetchedUser,user);
        }).then((model) => {
            return model.save();
        }).then((updatedModel) => {
            res.json({
                msg: 'model updated',
                updatedModel
            });
        }).catch((err) => {
            res.send(err);
        });

I think you should use $set in update query.Refer to the below query it is tested and working properly modify it according to requirement 我认为您应该在更新查询中使用$set 。参考下面的查询,它已经过测试并可以根据需要进行适当的修改

db.agreements.update({},{ $set:
  {
    "accountType":45,
    "address.address1":"india",
    "shareDealing.providers.uk.accountProviderId":984,
    }

}) })

You should use $set for that inside your Model.update . 您应该在Model.update内部使用$set Follow this link for an example if you need to, should solve the problem. 如果需要,请遵循链接作为示例,应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM