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

标签 node.js mongodb mongoose

我在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/

相关文章:

node.js - Docker实例端口管理

node.js - 通过 Visual Studio 部署时,Express 4 应用程序无法在 Azure 中运行

mongodb - 从本地主机到 cosmosDb 的 Mongorestore 失败, "disable retryable writes by specifying "retrywrites=false”

node.js - 如何在同一结果中显示两个单独的子文档?

mongodb - 了解 Golang 上下文超时

javascript - 基于条件的文档中各个字段的聚合计数

node.js - Mongoose 中的 Group by 给出了多个记录

node.js - 如何用node+express共享一个对象

node.js - sqlite last_insert_rowid 是原子的吗?

javascript - 如何将for循环中的值推送到mongo文档?