gpt4 book ai didi

node.js - Nodejs只能在数据库中创建一个用户

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:42 25 4
gpt4 key购买 nike

我在nodejs中使用api路由通过mongoose将用户添加到数据库中。标准的东西。然而,它对于一个用户来说可以完美地工作。然后,当我尝试创建另一个用户时,新用户已登录但未保存到数据库中。

感谢任何帮助。这是路线代码:

    app.get('/register' , function(req , res) {
res.sendFile(path.join(__dirname , '../public' , 'register.html'));
});
app.post('/api/register' , function(req, res) {
User.findOne({'local.email': req.body.email}, function(err, user) {
if(err) {
return res.json({
'message': err
});
}
if(user) {
return res.json({
'message': 'User already exists'
});
} else {
let newUser = new User();

newUser.local.email = req.body.email;
newUser.local.name = req.body.name;
newUser.local.password = newUser.setPassword(req.body.password);

newUser.save(function(err) {
var token;
token = newUser.generateJwt();
res.status(200);
res.json({
'token': token
});
});
}
});
});

架构:

const bcrypt = require('bcrypt-nodejs');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
let userSchema = new mongoose.Schema({
local: {
email: String,
name: String,
password: String
}
});
userSchema.methods.setPassword = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(10), null);
}
userSchema.methods.validatePassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
}
userSchema.methods.generateJwt = function() {
var expire = new Date();
expire.setDate(expire.getDate() + 7);

return jwt.sign({
_id: this._id,
email: this.local.email,
name: this.local.name,
exp: parseInt(expire.getTime() / 1000),
}, process.env.CONFIG_SR);
};
module.exports = mongoose.model('User' , userSchema);

最佳答案

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

let newUser = new User(); 

将其更改为

var newUser = new User():

关于node.js - Nodejs只能在数据库中创建一个用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46043588/

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