简体   繁体   中英

How to update a nested object in using Mongoose

Let say the current data on a given User is

{
            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

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.

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

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

})

You should use $set for that inside your Model.update . Follow this link for an example if you need to, should solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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