本文介绍了如果字段设置为null,则恢复为猫鼬的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在nodeJS中使用猫鼬.请考虑以下架构:

I am using mongoose with nodeJS. Consider the following schema:

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

这将创建一个新的Person文档,其名称设置为null.

This creates a new Person document with name set to null.

{
    name:null,
    age: 20
}

无论如何,是否要检查正在创建/更新的属性是否为null,如果为null,则将其设置为默认值.以下声明

Is there anyway to check if the property being created/updated is null and if it is null set it back to default. The following declaration

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

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

should create a new Person document with name set to default.

{
    name:"Human",
    age: 20
}

如何使用NodeJ和猫鼬来实现这一目标.

How would one implement this using NodeJs and mongoose.

推荐答案

有几种解决方法:

猫鼬中间件挂钩

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

    next();
});

ENUM

猫鼬验证猫鼬枚举

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

更新1

我想你必须这么做.

这只是带有枚举的ENUM的一个示例,您可以选择在ENUM中指定的值,即名称"只能具有人类"或无人类"值.

That is just an example of ENUM with enum you can only choose values that are specified in ENUM i.e. 'Name' can only have values of 'Human' or 'NONE-Human'.

这篇关于如果字段设置为null,则恢复为猫鼬的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 15:37
查看更多