我喜欢Mongoose附带的验证.我们试图弄清楚我们是否想要使用它,并忍受开销.有没有人知道在创建mongoose模式时是否提供对父集合的引用(在子模式中,将父对象的对象id指定为字段),这是否意味着每次您尝试保存文档时检查父集合是否存在refereneced对象id?
fer*_*sik 22
我正在使用中间件,在验证时执行元素搜索:
ExampleSchema = new mongoose.Schema({
parentId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Example'
}
});
ExampleModel = mongoose.model('Example', ExampleSchema);
ExampleSchema.path('parentId').validate(function (value, respond) {
ExampleModel.findOne({_id: value}, function (err, doc) {
if (err || !doc) {
respond(false);
} else {
respond(true);
}
});
}, 'Example non existent');
Run Code Online (Sandbox Code Playgroud)
Ami*_*noy 11
我正在使用mongoose-id-validator.效果很好
var mongoose = require('mongoose');
var idValidator = require('mongoose-id-validator');
var ReferencedModel = new mongoose.Schema({name: String});
var MySchema = new mongoose.Schema({
referencedObj : { type: mongoose.Schema.Types.ObjectId, ref: 'ReferencedModel'},
referencedObjArray: [{ type: mongoose.Schema.Types.ObjectId, ref: 'ReferencedModel' }]
});
MySchema.plugin(idValidator);
Run Code Online (Sandbox Code Playgroud)