如果字段设置为 null,则恢复为 mongoose 中的默认值

Revert to default value in mongoose if field is set to null

我正在使用带有 nodeJS 的猫鼬。考虑以下模式:

var PersonSchema = new mongoose.Schema({
    "name": {type: String, default: "Human"},
    "age": {type: Number, defualt:20}
});
mongoose.model('Person', PersonSchema);

var order = new Order({
    name:null
});

这将创建一个名称设置为空的新个人文档。

{
    name:null,
    age: 20
}

是否可以检查 属性 是否为 created/updated 是否为空,如果为空,则将其设置回默认值。以下声明

var order = new Order();
order.name = null;
order.save(cb);

应该创建一个新的 Person 文档,并将名称设置为默认值。

{
    name:"Human",
    age: 20
}

如何使用 NodeJs 和 mongoose 实现这一点。

好吧,有几种方法可以解决这个问题:

PRE-SAVE/PRE-VALIDATE 挂钩

Mongoose Middleware hooks

Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions.

PersonSchema.pre('save', function(next) {
    if (this.name === null) {
        this.name = 'Human';
    }

    next();
});

枚举

Mongoose Validation and Mongoose Enums

Strings have enum, match, maxlength and minlength validators.

var PersonSchema = new mongoose.Schema({
    "name": {type: String, default: "Human", enum: ['Human', 'NONE-Human']},
    "age": {type: Number, defualt:20}
});

更新 1

If I have 20 fields where I want to check whether they are set to null, do I have to repeat this.field = default for all of them?

我想你必须这样做。

What does NONE-Human in enums do? I could not find documentation for this online.

这只是带有枚举的 ENUM 示例,您可以 选择在 ENUM 中指定的值,即 'Name' 只能具有 'Human' 的值或 'NONE-Human'.

回答这个问题有点晚了,但更通用的方法是不要在 pre hook 中再次对字段进行硬编码。

相反,让我们使用模式本身遍历字段并检查具有 default 值并明确设置为 null 的字段。在这种情况下,我们将其设置为默认值。

PersonSchema.pre('save', function(next) {
  const self = this;
  Object.keys(this.schema.paths).forEach(function(key) {
    if(self.schema.paths[key].options.default && self[key] === null) {
      self[key] = self.schema.paths[key].options.default;
    }
  });
  next();
});

更晚的回答。我正在寻找一个更简单的解决方案并遇到了这个问题。以为我会分享我最终做的事情。

db.Person.create({
   name: usersName || "Human",
   age: usersAge,
})