Javascript Mongoose:如何验证至少存在以下一个字段?
这是我的用户模式:Javascript Mongoose:如何验证至少存在以下一个字段?,javascript,mongoose,Javascript,Mongoose,这是我的用户模式: var userSchema = mongoose.Schema({ username: { type: String, required: true, unique: true }, role: String, auth: { hashedPassword: { type: String, select: false }, facebookToken: { type: String, select: false }, twitterTok
var userSchema = mongoose.Schema({
username: { type: String, required: true, unique: true },
role: String,
auth: {
hashedPassword: { type: String, select: false },
facebookToken: { type: String, select: false },
twitterToken: { type: String, select: false },
googleToken: { type: String, select: false }
},
});
我想验证是否至少存在一个auth
属性。我该怎么做
在查看用于自定义验证的字段时,似乎只能在给定字段上添加自定义验证程序。我认为这应该可以:
var user = require('./path/to/userSchema');
var detectAuthMethod = function(userName, callback){
user.findOne(username: username, function(err, doc){ // Finds user by userName string. userName is required.
if(err) throw err;
for (var key in doc.auth){ // Iterates through all doc.auth keys
if (doc.auth.hasOwnProperty(key){ // Checks if they key has been set
callback(null, key); // Callback "return". Status succes (null), and response is they setted key.
}
}
callback('err, there is no valid key.'); // Callback "return". Status is an error message, and there is no response key.
});
}
然后您可以从源文件调用函数,如下所示:
detectAuthMethod('bob', function(err, key){
if(err) throw err;
console.log('Bob has been authenticated with %s key', key);
});
如果需要从其他地方(而不是源文件)调用该函数,在源文件末尾添加以下内容就足够了:
module.exports.detectAuthMethod = detectAuthMethod;
然后需要其他地方的源文件,并像往常一样使用它。我想您需要一个新的源文件
您可以在主架构中使用:
const UserSchema = mongoose.Schema({
username: { type: String, required: true, unique: true },
role: String,
auth: {
type: authSchema,
required: true,
validate: {
validator: function(s) {
const MIN_LENGTH = 6;
return (
this.auth.hashedPassword.length >= MIN_LENGTH ||
this.auth.facebookToken.length >= MIN_LENGTH ||
this.auth.twitterToken.length >= MIN_LENGTH ||
this.auth.googleToken.length >= MIN_LENGTH
);
}
}
}
});
但这还不够。正如您可能已经知道的,验证不会在未指定值的属性上运行。因此,当我最近尝试在POST端点上执行类似的操作时,我添加了代码,为我想要强制验证的所有属性分配空字符串值
例如,在Express端点中,您可以执行以下操作:
const postUser = async (req, res) => {
const postedUser = req.body;
let userObj = Object.assign({}, postedUser);
userObj.auth.hashedPassword = userObj.auth.hashedPassword || "";
userObj.auth.facebookToken = userObj.auth.facebookToken || "";
userObj.auth.twitterToken = userObj.auth.twitterToken || "";
userObj.auth.googleToken = userObj.auth.googleToken || "";
…在你验证你的模型之前。如果有人像我一样好奇,你可以这样验证
const schema = new Schema({
a: String,
b: {
type: String,
required: function() { return this.a === 'test'; } // Only required if a equals 'test'
}
});
const schema = new Schema({
a: String,
b: {
type: String,
required: function() { return this.a === 'test'; } // Only required if a equals 'test'
}
});