【问题标题】:check if username and email is unique in database检查用户名和电子邮件在数据库中是否唯一
【发布时间】:2017-12-15 16:46:27
【问题描述】:

尝试在网上搜索了 2 天,但仍然找不到具体的答案。我有以下用于用户路由和模型的 node.js 代码。如何检查用户名和电子邮件是否从未出现在 MongoDB 中,如果有则提示用户消息?

型号:

var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');

// User Schema
var UserSchema = mongoose.Schema({
  username:{type: String , required:true, index: true, unique:true},
  email:{type: String, required:true, index: true, unique:true},
  password:{type: String, required:true}
});

module.exports = mongoose.model('User', UserSchema)

路线:

var express = require('express');
var router = express.Router();
var User = require('../models/user');
var bcrypt = require('bcryptjs');

// Get Homepage
router.get('/', function(req, res){
    res.render('index');
});

router.get('/register',function(req,res){
    res.render('register');
});

// submit form
router.post('/submit', function(req, res){

    // retrieve data from posted HTML form
    var username = req.body.username;
    var email = req.body.email;
    var password = req.body.password;
    var password_confirm = req.body.password_confirm;

    // express validator
    req.checkBody('username','Username is required').notEmpty();
    req.checkBody('email','Email is required').notEmpty();
    req.checkBody('email','Invalid email').isEmail();
    req.checkBody('password','Password is required').notEmpty();
    req.checkBody('password','Password must contain at least 6 characters').isLength({min:6});
    req.checkBody('password_confirm','Password mismatch').equals(req.body.password);

    // store the errors
    var errors = req.validationErrors();
    if(errors){res.render('register',{errors:errors});}
    else {
        // hash password
        var salt = bcrypt.genSaltSync(10);
        var hash = bcrypt.hashSync(password, salt);
        password=hash;

        // load data into model
        var newUser = new User ({username:username, email:email, password:password});
        // save the new user
        newUser.save(function(err,newUser){
            if(err){console.error(err);}
            // console.error is same, but in stderr form
            else{
                console.log('new user saved successfully');
                console.log(newUser);
            }
        });
        res.redirect('/');
    }
});

module.exports = router;

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案1】:
    app.post('/authenticate', function(req, res) {
      var user = new User({
        username: req.body.username
      });
    
      user.save(function(err) {
        if (err) {
          if (err.name === 'MongoError' && err.code === 11000) {
            // Duplicate username
            return res.status(500).send({ succes: false, message: 'User already exist!' });
          }
    
          // Some other error
          return res.status(500).send(err);
        }
    
        res.json({
          success: true
        });
    
      });
    })
    

    您必须捕获错误并将其返回到应用程序的前端。上面的代码应该演示如何通过使用服务器状态500 来实现这一点。关于搜索网络,这个答案和问题与上一个问题非常相似:

    How to catch the error when inserting a MongoDB document which violates an unique index?

    我希望这在一定程度上有所帮助。

    【讨论】:

    • 感谢您的回复。但我仍然可以将具有相同用户名的新条目成功保存到 mongodb 中。当我使用 console.log(err) 时,它不会产生任何错误。我检查了您提供的另一个案例的链接,至少该案例有错误消息。你知道为什么我没有任何错误吗?
    • 因为您可能没有以相同的方式定义变量。在这里,我看到您正在使用此 var errors = req.validationErrors(); 尝试控制台日志记录 errors 并查看实际出现的情况。
    • 与电子邮件相比,是否有区分用户名错误的方法?因为我很确定 err.name 和 err.code 在两者之间保持不变。我之所以好奇是因为我想让用户知道这两者中的哪一个已经在使用中,而不必猜测它是电子邮件还是用户名
    • @Jake 您好,很抱歉回复晚了。为此检查特定的 MongoDB 错误代码。另一种方法是创建 find 查询并搜索重复项。
    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2016-05-09
    • 2014-03-15
    相关资源
    最近更新 更多