gpt4 book ai didi

node.js - 在 Node.js 中使用 MongoDB 使用电子邮件或用户名登录

转载 作者:IT老高 更新时间:2023-10-28 13:26:27 25 4
gpt4 key购买 nike

我想知道是否有办法让用户同时使用用户名或电子邮件登录我搜索了很多次,但没有找到一种工作方法。我不知道如何做到这一点,请尽可能提供最简单的方法。这是我的用户架构的样子:

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
};
}
elseif(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();
};

关于node.js - 在 Node.js 中使用 MongoDB 使用电子邮件或用户名登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41017254/

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