gpt4 book ai didi

node.js - Mongoose 可选的最小长度验证器?

转载 作者:行者123 更新时间:2023-12-05 08:33:31 26 4
gpt4 key购买 nike

我怎样才能有一个可选的 string 字段类型和 minlength。文档 (linked here)不细说这个?我一直在努力:

var schema = mongoose.Schema({
name: { type: String, required: true, maxlength: 255 },
nickname: { type: String, minlength: 4, maxlength: 255 }
});

我尝试的每个变体都会返回某种类型的错误。

我的目标是评估 minlengthmaxlength 仅当已提供值时。

最佳答案

简答:写一个 mongoose 插件。

长答案:

您可以根据需要向模式添加额外的属性。您通常会编写一个 Mongoose Plugin 来实际对它们执行某些操作。这方面的一个例子是 mongoose-hidden允许您在转换期间将某些字段定义为隐藏的插件:

var userSchema = new mongoose.Schema({
name: String,
password: { type: String, hide: true }
});
userSchema.plugin(require('mongoose-hidden'));

var User = mongoose.model('User', userSchema, 'users');
var user = new User({ name: 'Val', password: 'pwd' });
// Prints `{ "name": "Val" }`. No password!
console.log(JSON.stringify(user.toObject()));

请注意 password: 字段中的 hide: true 属性。该插件覆盖了 toObject() 函数,自定义版本删除了对属性的查找并删除了该字段。

这是插件的主体。第 4 行检查是否存在 schemaType.options.hide 属性:

function HidePlugin(schema) {
var toHide = [];
schema.eachPath(function(pathname, schemaType) {
if (schemaType.options && schemaType.options.hide) {
toHide.push(pathname);
}
});
schema.options.toObject = schema.options.toObject || {};
schema.options.toObject.transform = function(doc, ret) {
// Loop over all fields to hide
toHide.forEach(function(pathname) {
// Break the path up by dots to find the actual
// object to delete
var sp = pathname.split('.');
var obj = ret;
for (var i = 0; i < sp.length - 1; ++i) {
if (!obj) {
return;
}
obj = obj[sp[i]];
}
// Delete the actual field
delete obj[sp[sp.length - 1]];
});

return ret;
};
}

我的观点是......

...如果您编写一个 mongoose 插件(例如,可能是“MinLengthPlugin”),您可以在所有模式上重复使用它而无需编写任何额外的代码。在插件中,您可以用类似的东西覆盖功能:

module.exports = function MinLenghPlugin (schema, options) {

schema.pre('save', myCustomPreSaveHandler);

var myCustomPreSaveHandler = function() {
// your logic here
}
};

关于node.js - Mongoose 可选的最小长度验证器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38937020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com