在猫鼬模型上需要帮助

时间:2019-02-23 05:30:48

标签: database mongodb express mongoose

我是mongoDB和mongoose的新手。但是我想做的是能够通过他们的电子邮件访问我存储在数据库中的用户,如果成功检索到用户,我将把他们编写的密码与存储在数据库中的哈希密码进行比较

这就是我的架构

UserSchema

var UserSchema = new Schema({
  firstName: { type: String, required: true }, //require makes it so that the fields can't be left blank
  lastName: {type: String, required: true},
  emailAddress: {type: String, required: true},
  password: {type: String, required: true}      
});
var User = mongoose.model("User", UserSchema);

我在route.js文件中使用basic-auth软件包,以便在邮递员中测试此api,这是我被卡住的部分, const user = User.find({ emailAddress':certificate.name,user.emailAddress}); 我在整理查询以访问数据库中的用户电子邮件时遇到困难

    //This middle-where function will authenticate users
const authenticateUser = (req, res, next) => {
  let message = null;

  // Parse the user's credentials from the Authorization header.
  const credentials = auth(req);

  // If the user's credentials are available...
  if (credentials) {
    // Attempt to retrieve the user from the data store
    // by their email (i.e. the user's "key"
    // from the Authorization header).
    const user = User.find({'emailAddress': credentials.name, user.emailAddress} );

    // If a user was successfully retrieved from the data store...
    if (user) {
      // Use the bcryptjs npm package to compare the user's password
      // (from the Authorization header) to the user's password
      // that was retrieved from the data store.
      const authenticated = bcryptjs
        .compareSync(credentials.pass, user.password);

在此快速路由器中,我仅在通过身份验证后才返回用户

//GET /api/users 200, THIS WORKS IN POSTMAN
//This Route returns the currently authenticated user,     
router.get('/users', authenticateUser, (req, res) => {
  //within the route handler, the current authenticated user's information is retrieved from the Request object's currentUser property:
  const user = req.currentUser;
//we use the Response object's json() method to return the current user's information formatted as JSON:
  res.json({
    firstName: user.firstName,
    lastName: user.lastName,
  });
});

有人可以帮忙吗?供参考,这是我的仓库https://github.com/SpaceXar20/rest_api-mongo-p9

1 个答案:

答案 0 :(得分:0)

在这里,find()的方法是错误的 它应该是带有异步等待的回调或exec()。这种情况下只使用回调 所以不用这段代码

const user = User.find({'emailAddress': credentials.name, user.emailAddress} );

使用此代码

    User.find({emailAddress:user.emailAddress},(err,user)={
      if(err) throw err;
      // do what you please
    if (user) {

      bcrypt.compare(password,hash,function(err,isMatch){
    if(err) callback(err,null);
    callback(null,isMatch);

});
    } );