Node.js 猫鼬模型验证范围
我将从node、express和nodejs(我来自PHP环境)开始我的冒险。虽然大部分内容都非常简单,但我希望保持模型的整洁,当验证变得复杂时,我不知道如何分离验证内容 我的产品型号:Node.js 猫鼬模型验证范围,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我将从node、express和nodejs(我来自PHP环境)开始我的冒险。虽然大部分内容都非常简单,但我希望保持模型的整洁,当验证变得复杂时,我不知道如何分离验证内容 我的产品型号: var mongoose = require('mongoose'); var schema = new mongoose.Schema({ title: String, content: String, update_date: Date, }); var model = mo
var mongoose = require('mongoose');
var schema = new mongoose.Schema({
title: String,
content: String,
update_date: Date,
});
var model = mongoose.model ('Page', schema);
exports = module.exports = function (db) { return db.model('Item');};
我的问题是:
- 在“创建”范围字段标题中,内容应为必填项
- 在“更新”范围字段中,应要求更新日期,并使用日期类型进行验证
- 在“清除”范围字段中,内容和更新日期验证为空
mongoose
为您提供了很大的灵活性,并且已经预装了验证机制。除非您真的需要,否则重新构建此功能是没有意义的,而且这样做会在您的路线中产生大量噪音。我会考虑与本地MangoDB驱动程序和您自己的自定义逻辑进行同源修改,如果您觉得它与本地驱动程序不太难相处,但是如果项目将要增长,models/
User/
index.js
statics.js
methods.js
validators.js
middleware.js
routes/
views/
在models/User/index.js
中,我们创建了模式,并添加了一些用于文件拆分的粘合代码,这些代码可以作为require('./models/User')
所需:
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
name: String,
password: String,
role: String
});
userSchema.statics = require('./statics');
userSchema.methods = require('./methods');
// This will go through each exports in the validators file and attach
// the exported function as a validator. You're validators file should
// name each validator after the field in which it intends to validate.
// See below for example validators file.
var validators = require('./validators');
Object.keys(validators).forEach(function (validator) {
userSchema.path(validator).validate(validators[validator]);
return;
});
// Do the following for each type of middleware you use in the model
var preSave = require('./middleware').preSave;
preSave.forEach(function (middleware) {
userSchema.pre('save', middleware);
return;
});
module.exports = mongoose.model('User', userSchema);
然后,我们可以将validators.js
文件设置为:
exports['name'] = function () { /* validation code here */ };
exports['password'] = function () { /* validation code here */ };
exports['role'] = function () { /* validation code here */ };
//etc, etc, etc.
通过滚动一个插件为您提供这个接口,而不需要所有的样板文件,您可以更进一步。我还没有走这条路,但是mongoose
的插件开发非常简单:
请记住,express
不是按照RoR或Yii建模的。在ruby中,Sinatra与nodejs世界之外的express
最接近。(我相信,在Sinatra之后的建模是TJ的起点,然后该项目经过多年的发展演变为目前的状态)