我是node.js的新手,正在构建用户登录系统,但出现错误 如 注册新用户时遇到此错误
MongoDB已连接
(node:12592) UnhandledPromiseRejectionWarning: TypeError: user is not a constructor
at User.findOne.then.user (C:\Users\AKASH TOMAR\Desktop\miniproject\routes\users.js:59:35)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12592) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12592) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:12592) UnhandledPromiseRejectionWarning: TypeError: user is not a constructor
at User.findOne.then.user (C:\Users\AKASH TOMAR\Desktop\miniproject\routes\users.js:59:35)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12592) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
我没有走错地方,请帮帮我,因为明天我必须在大学里证明自己,我也对我的代码进行了注释,以确保他们站得住脚。
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
//User model
const User = require('../models/User');
//Login page
router.get('/login',(req,res)=>res.render('login'));
//register page
router.get('/register',(req,res)=>res.render('register'));
//Register Hnadle
router.post('/register',(req,res)=>{
const {name,email,password,password2 } = req.body;
let errors = [];
//check required fields
if(!name || !email || !password || !password2){
errors.push({msg: 'Please fill in all fields'});
}
//check passwords match
if(password !== password2){
errors.push({msg: 'Passwords do not match'});
}
//check password length
if(password.length < 6){
errors.push({msg:'Password should be at least 6 chracters'});
}
if(errors.length>0){
res.render('register',{
errors,
name,
email,
password,
password2
});
}else{
//validation passed
User.findOne({email: email})
.then(user => {
if(user){
//user exists
errors.push({msg: 'Email is already registered'});
res.render('register',{
errors,
name,
email,
password,
password2
});
}else {
const newUser = new user({
name,
email,
password
});
//hash password
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => {
req.flash(
'success_msg',
'You are now registered and can log in'
);
res.redirect('/users/login');
})
.catch(err => console.log(err));
});
});
}
});
}
});
module.exports = router;
答案 0 :(得分:1)
您的代码说
const newUser = new user({
,但是在这种情况下,user
是您的承诺then
中的变量。您想要User
这是您的mongo类。