Подтвердить что ты не робот

Сделать все поля обязательными в Mongoose

Mongoose по умолчанию делает все поля не обязательными. Есть ли способ сделать все необходимые поля без изменения каждого из них:

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

к

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

Это будет очень уродливо, так как у меня их много.

4b9b3361

Ответ 1

Я закончил это:

r_string = 
  type: String
  required: true 

r_number = 
  type: Number
  required: true

и далее для других типов данных.

Ответ 2

Вы можете сделать что-то вроде:

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

или для всех attrs (с использованием подчеркивания, которое является удивительным):

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

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

var Dimension = mongoose.schema(schema);

Ответ 3

Все свойства полей находятся в schema.paths[attribute] или schema.path(attribute);

Один правильный способ: определить, когда поле НЕ требуется,

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

и сделайте все необходимое по умолчанию:

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

AllFieldsRequiredByDefautlt(Myschema)

Подчеркнутый способ:

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

Проверьте это:

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

Ответ 4

Хорошо, вы могли бы написать функцию плагина схемы мангуста, которая прошла объект схемы и скорректировала ее, чтобы сделать каждое поле обязательным. Тогда вам понадобится только 1 строка для каждой схемы: Dimension.plugin(allRequired).

Ответ 5

Mongoose не предоставил метод установки всех полей, но вы могли бы сделать это рекурсивно.

Как упоминал Питер, вы можете подключить его, чтобы повторно использовать код.

Рекурсивная настройка:

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

Ответ 6

Я не уверен, есть ли более простой способ сделать это в Mongoose, но я бы сделал следующее в вашей среде IDE/editor:

Перечислите свои поля, как обычно:

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

Затем найдите и замените на String и замените его на {type: String, required: true}, Предоставление вам:

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

Затем сделайте то же самое для Number и других типов.

Ответ 7

Основываясь на предыдущих ответах, приведенный ниже модуль сделает поля обязательными по умолчанию. Предыдущие ответы не возвращали вложенные объекты/массивы.

Использование:

const rSchema = require("rschema");

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

Node модуль:

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