我有以下代码:

var express = require('express');
const app = express();
const mongoose = require('mongoose');
var bcrypt = require('bcrypt');
const jwt2 = require('jsonwebtoken');
const User = require('./models/user.js');
app.post('/api/login', async function (req, res){
  try  {
    const hashedPassword = await bcrypt.hash(req.body.password, 10);
    console.log(hashedPassword);
    console.log(await bcrypt.compare('testtest',hashedPassword));
    var user = new User({ id: req.body.id, username: req.body.username, password: hashedPassword });
    user.save(function (err, User) {
      if (err) return console.error(err);
      console.log("Saved successfully");
    });
    // TODO: Implement proper user check!
    if (user.username !== 'test' && await bcrypt.compare('testtest', hashedPassword) !== true )
    throw TypeError("Bah! Wrong username and password!");
    // ----TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO
    jwt2.sign({user}, 'secrethere', { expiresIn: '15min'}, (err, token) =>{
    res.json({
      token
    });
  });
  } catch (err) {
    res.status(500).send()
    console.log(err);
  }

});


我的user.js:

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({

    loginId: String,
    firstname: String,
    lastname: String,
    eMail: String,
    password: String,
    active: Boolean

});

module.exports = mongoose.model("User", userSchema);


问题在于,即使代码被定义为保存更多密码(ID,用户名,密码),该代码也仅将密码哈希保存在数据库中。我做错了什么?

最佳答案

您使用“ id”和“用户名”

var user = new User({ id: req.body.id, username: req.body.username, password: hashedPassword });


而且您的架构不包含这些字段
尝试:

var user = new User({ loginId: req.body.id, firstname: req.body.username, password: hashedPassword });

关于javascript - 由于某些原因, Mongoose 只保存密码哈希,而不保存所有字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59159412/

10-16 21:22