简体   繁体   中英

How to leave a field in MongoDB without any changes in an update operation?

I have an object to update a document in MongoDB, eg:

let data = {"id": 123, "user": "abc", "is_invalid": "true"}

When the field "is_invalid" became true for the first time - I'm adding a field of "invalid_date" . If "is_invalid": "false" I remove it. In case that the document has "is_invalid": "true" , and "invalid_date" already, and I get the object to update again, I don't want the "invalid_date" to change, but stay the same. How can I do it?

Here's my code:

let id = data.id;

delete data.id;

let update = {$set: data};

if (user.is_invalid) {
   update.$set.inactivate_time = new Date(Date.now());
} else {
   update.$unset = {
      inactivate_time: 1
   };
}

mongo.collection('users').update(
                {
                    id: id
                },
                update, done);

I feel you need to add extra condition in your code, if you already have the access on object. Lets consider a scenario where you will have true and date in the object then you can do following.

let data = {"id": 123, "user": "bcd", "is_invalid": "true", "invalid_date":"2021-03-10"}

//you can have a first condition as 

if(data.is_invalid && data.invalid_date){
return; //simply return
}
...
...
//Rest of the code
..
..

Your need to do something like this as update query cannot findOne it just updates/overwrites the receving data.

const user = await mongo.collection('users').findOne({id: id});
if(!user)
   throw 'No user found'
if(user.is_invalid && !user.invalid_date){
    user.invalid_date = getting.invalid_date;
}
await user.save();

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