我想知道是否有办法让用户同时使用用户名或电子邮件登录 我搜索了很多次但没有找到可行的方法。我不知道如何做到这一点,如果可能的话,请以最简单的方式提供帮助。这是我的用户架构:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
fullname: String,
username: { type : String , lowercase : true , unique: true , required: true, minlength: 3, maxlength: 10},
email: String,
password: String,
mobile: String,
gender: String,
profession: String,
city: String,
country: String,
joining: {type: Date, default: Date.now}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
附加信息:我正在nodejs之上工作。 非常感谢任何帮助。 谢谢
//the simple example of login//
router.post('/users/login', function(req, res) {
var users = req.app;
var email = req.body.email;
var password = req.body.password;
var username = req.body.username;
var data;
if (email.length > 0 && password.length > 0) {
data = {
email: email,
password: password
};
}
else if(username.length > 0 && password.length > 0) {
data = {
username: username,
password: password
};
} else {
res.json({
status: 0,
message: err
});
}
users.findOne(data, function(err, user) {
if (err) {
res.json({
status: 0,
message: err
});
}
if (!user) {
res.json({
status: 0,
msg: "not found"
});
}
res.json({
status: 1,
id: user._id,
message: " success"
});
})
} else {
res.json({
status: 0,
msg: "Invalid Fields"
});
}
});
//and if you have to create schema
var db_schema = new Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
unique: true
},
});
// define this in your db.js
var login_db = mongoose.model('your_db_name', db_schema);
return function(req, res, next) {
req.app = login_db;
next();
};
我知道我回答这个问题已经晚了。前面的答案包含了大部分答案,但您不能简单地通过发送电子邮件来检查字符串的长度。 length 并将其传递给 findOne 函数。在检查之前使用诸如 Joi 之类的库进行某种验证。这将简单地检查电子邮件是否包含任何内容或用户名。
if (email) {
data = {
email: email
};
} else if(username) {
data = {
username: username
};
} else {
res.json({
status: 0,
message: err
});
}
const user = await User.findOne(data)