检查唯一的电子邮件和用户名后,新用户不会保存到MongoDB中

时间:2019-12-12 10:11:56

标签: node.js mongodb express mongoose bcrypt

我是网络开发领域的新手。我想创建一个“用户注册和登录”应用程序。但是我无法在注册点将唯一的用户信息保存到MongoDB中。这是我的代码...

型号:

    const mongoose = require('mongoose');
    // User Schema
    const UserSchema = mongoose.Schema( {
       name: { type: String, required: true },
       email: { type: String, required: true, unique: true },
       username: { type: String, required: true, unique: true },
       password: { type: String, required: true }
    } );
    const User = module.exports = mongoose.model( 'User', UserSchema );

控制器:

    const express = require('express');
    const router = express.Router();
    const passport = require('passport');
    const bcrypt = require('bcryptjs');
    const Users = require('../models/userModel');

    // post route for Register Process
    router.post( '/register', ( req, res ) => {
       const name = req.body.name;
       const email = req.body.email;
       const username = req.body.username;
       const password = req.body.password;
       const confirmPassword = req.body.confirmPassword;

       // Check email or username already exists in DB
       Users.find( { $or: [ {email: email}, {username: username} ] }, ( err, users ) => {
          if( err ){ return console.log( err ); }
          else{
             // If email or username already exists in DB
             if( users ){
                if( users.length > 0 ){
                   for( let i = 0; i < users.length; i++ ){
                      let hasEmail = ( users[i].email == email );
                      let hasUsername = ( users[i].username == username );
                      if( hasEmail ){
                         return console.log( 'Email already registered.' );
                      }
                      else if( hasUsername ){
                         return console.log( 'Username already taken.' );
                      }
                   }
                }
             }
             else{

                // If email or username is unique / not exists in DB
                // then save / create a new user
                let newUser = new Users( {
                   name: name,
                   email: email,
                   username: username,
                   password: password,
                   confirmPassword: confirmPassword
                } );

                // Password hashing
                bcrypt.genSalt( 10, ( err, salt ) => {
                   bcrypt.hash( newUser.password, salt, ( err, hash ) => {
                      if( err ){ return console.log( err ); }
                      newUser.password = hash;

                      // New user save in DB / create a new user
                      newUser.save( ( err ) => {
                         if( err ){
                            return console.log( err );
                         } else{
                            return console.log( 'You have registered successfully' );
                         }
                      } );
                   } );
                } );
             }
          }
       } );
    } );
    module.exports = router;

所有代码(带有服务器)都可以。如果输入emailusername,则DB中已经存在任何人,然后会收到一条error消息。但是,如果值是唯一的,则newUser.save()不会触发(不会保存到数据库中),并且不会在控制台或浏览器中显示任何error消息,即页面连续加载。在这里,我使用$or: [ {email: email}, {username: username} ]通过emailusername查找现有用户。

如何解决此问题?请帮帮我。

2 个答案:

答案 0 :(得分:0)

当没有匹配项时,find()返回[],因此,请按如下所示修改代码:

删除if( users ){并直接检查长度

 if( users.length > 0 ){
//do stuff for existing user
 } else {
      let newUser = new Users( {
       name: name,
       email: email,
       username: username,
       password: password,
       confirmPassword: confirmPassword
     } );

//save function
}

在您的情况下,您的if( users)将始终得到满足,并且不会执行将触发else的{​​{1}}部分

答案 1 :(得分:0)

我相信是因为这一行if( users ) {}。即使您提供唯一的电子邮件和密码,users也将是一个空数组。在这种情况下:

if (users) {
   console.log('Have users'); <- This will get executed although email and username is unique
}

相反,您可以这样做:

if (users && users.length > 0) {
   console.log('Have users');
}

此外,您的架构中没有confirmPassword字段。

建议:您的代码嵌套过多。您可以像这样简化代码。

if( err ) {
  console.log( err );
  return;
}
// else is not needed
if( users && users.length > 0 ){
  // DO YOUR STUFF

  return;
}
// else is not needed again
let newUser = new Users( { ... } );