node.js 使 Mongoose 中的所有字段都为必填项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19762430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:11:12  来源:igfitidea点击:

Make all fields required in Mongoose

node.jsmongodbmongooseschema

提问by maxko87

Mongoose seems to default to make all fields not required. Is there any way to make all the fields required without changing each of:

Mongoose 似乎默认使所有字段都不需要。有没有办法在不更改每个字段的情况下制作所有必需的字段:

Dimension = mongoose.Schema(
  name: String
  value: String
)

to

Dimension = mongoose.Schema(
  name:
    type: String
    required: true
  value: 
    type: String
    required: true
)

It'll get really ugly since I have a lot of these.

因为我有很多这些,它会变得非常丑陋。

采纳答案by maxko87

I ended up doing this:

我最终这样做了:

r_string = 
  type: String
  required: true 

r_number = 
  type: Number
  required: true

and on for the other data types.

以及其他数据类型。

回答by 190290000 Ruble Man

You could do something like:

你可以这样做:

var schema = {
  name: { type: String},
  value: { type: String}
};

var requiredAttrs = ['name', 'value'];

for (attr in requiredAttrs) { schema[attr].required = true; }

var Dimension = mongoose.schema(schema);

or for all attrs (using underscore, which is awesome):

或者对于所有属性(使用下划线,这很棒):

var schema = {
  name: { type: String},
  value: { type: String}
};

_.each(_.keys(schema), function (attr) { schema[attr].required = true; });

var Dimension = mongoose.schema(schema);

回答by Flint

All fields properties are in schema.paths[attribute]or schema.path(attribute);

所有字段属性都在schema.paths[attribute]schema.path(attribute)

One proper way to go : define when a field is NOT required,

一种正确的方法:定义何时不需要字段,

Schema = mongoose.Schema;
var Myschema = new Schema({
    name : { type:String },
    type : { type:String, required:false }
})

and make them all required by default :

并使它们全部默认为必需:

function AllFieldsRequiredByDefautlt(schema) {
    for (var i in schema.paths) {
        var attribute = schema.paths[i]
        if (attribute.isRequired == undefined) {
            attribute.required(true);
        }
    }
}

AllFieldsRequiredByDefautlt(Myschema)

The underscore way :

下划线方式:

_=require('underscore')
_.each(_.keys(schema.paths), function (attr) {
    if (schema.path(attr).isRequired == undefined) {
        schema.path(attr).required(true);
    }
})

Test it :

测试一下:

MyTable = mongoose.model('Myschema', Myschema);
t = new MyTable()
t.save()

回答by Peter Lyons

Well you could write a mongoose schema plugin function that walked the schema object and adjusted it to make each field required. Then you'd just need 1 line per schema: Dimension.plugin(allRequired).

好吧,您可以编写一个 mongoose 模式插件函数,该函数遍历模式对象并对其进行调整以使每个字段都需要。那么每个架构只需要 1 行:Dimension.plugin(allRequired).

回答by chuyik

Mongoose didn't provide the method of setting all fields, but you could do it recursively.

Mongoose 没有提供设置所有字段的方法,但是你可以递归地设置。

Like Peter mentioned, you could pluginize it in order to reuse the code.

就像彼得提到的那样,您可以将其插件化以重用代码。

Recursively setting:

递归设置:

// game.model.js
var fields = require('./fields');
var Game = new Schema({ ... });

for(var p in Game.paths){
  Game.path(p).required(true);
}

Pluginized:

插件化:

// fields.js
module.exports = function (schema, options) {
  if (options && options.required) {
    for(var p in schema.paths){
      schema.path(p).required(true);
    }
  }
}

// game.model.js
var fields = require('./fields');
var Game = new Schema({ ... });
Game.plugin(fields, { required: true });

回答by Samuel O'Malley

I'm not sure if there's an easier way to do it in Mongoose, but I would do the following in your IDE/editor:

我不确定在 Mongoose 中是否有更简单的方法,但我会在您的 IDE/编辑器中执行以下操作:

List out your fields as you would normally:

像往常一样列出您的字段:

Dimension = mongoose.Schema(
  name: String
  value: String
)

Then do a find and replace on Stringand replace it with {type: String, required: true},Giving you:

然后进行查找和替换String并将其替换为{type: String, required: true},Giving you:

Dimension = mongoose.Schema(
  name: {type: String, required: true},
  value:  {type: String, required: true},
)

Then do the same for Numberand other types.

然后对Number和其他类型执行相同的操作。

回答by koga73

Building on the previous answers, the module below will make fields required by default. The previous answers did not recurse nested objects/arrays.

在前面的答案的基础上,下面的模块将默认设置为必填字段。以前的答案没有递归嵌套对象/数组。

Usage:

用法:

const rSchema = require("rschema");

var mySchema = new rSchema({
    request:{
        key:String,
        value:String
    },
    responses:[{
        key:String,
        value:String
    }]
});

Node module:

节点模块:

const Schema = require("mongoose").Schema;

//Extends Mongoose Schema to require all fields by default
module.exports = function(data){
    //Recursive
    var makeRequired = function(schema){
        for (var i in schema.paths) {
            var attribute = schema.paths[i];
            if (attribute.isRequired == undefined) {
                attribute.required(true);
            }
            if (attribute.schema){
                makeRequired(attribute.schema);
            }
        }
    };

    var schema = new Schema(data);
    makeRequired(schema);
    return schema;
};