简体   繁体   中英

How to exclude fields from being “upsert-ed” in Mongoose?

var UserData = function(){
    var self = this;
    this.schema = Schema({
        userID: String,
        firstName: String,
        lastName: String,
        ...
        //many other fields.
        ...
        isActive: {type: "Boolean", default: true}
    },  { collection: 'UserData' });

    this.model = db.model('UserData', self.schema);

    this.upsert = function(object){
        //some logic
        self.model.update({userID: object.userID}, object, {upsert: true}, function(err){...});
    };
}

This code work fine except for the isActive will be overwritten during the upsert.

I want to implement the logic like this:

  1. Default isActive to be true for new record.
  2. When do upsert, keep isActive unchanged.

How to achieve that? Thanks in advance!

Convert the document to an object and remove the property that you don't want to write. Then upsert the object.

this.upsert = function (doc) {
    var object = doc.toObject();
    delete object.isActive;

    self.model.update({userID: object.userID}, object, {upsert: true}, function(err){...});
};

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