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

标签 node.js mongodb mongoose mongoose-schema mongoose-populate

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

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/

相关文章:

javascript - Node.js http 请求未结束

MongoDB - 计算包含数组元素的数组中的值的$sum

mongodb - 你如何限制 Mongo 中的数组子元素?

javascript - 使用 Mongoose 查询虚拟字段

node.js - 类型错误 : Cannot read property 'substr' of undefined - source-node. js

node.js - Aerospike - 在嵌套对象中添加新的键/值对

node.js - foo.find(...).execFind 不是函数 - Mongoose 模式模型

Javascript - Mongodb Collection 的模型查找方法不适用于过滤条件

javascript - 对 Node、NPM、Bower 感到困惑,并将其用于 Bootstrap

javascript - 如何修复 CRUD 应用程序中的 404(未找到)错误?