如何在Mongoose中排除字段“upsert-ed”?

时间:2013-02-21 18:33:49

标签: javascript node.js mongoose upsert

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){...});
    };
}

此代码正常工作,除了 isActive 将在upsert期间被覆盖。

我想实现这样的逻辑:

  1. 默认 isActive 对新记录为真。
  2. 何时进行upsert,保持 isActive 不变。
  3. 如何实现?提前谢谢!

1 个答案:

答案 0 :(得分:1)

将文档转换为对象并删除您不想编写的属性。然后插入对象。

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

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