【问题标题】:Mongoose findOne function is not working with authenticationMongoose findOne 功能不适用于身份验证
【发布时间】:2018-10-06 20:37:59
【问题描述】:

我正在这里制作模型:

// user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');

// Define collection and schema for Users
let User = new Schema(
  {
    firstName: String,
    lastName: String,
    emailaddress: String,
    password: String,
  },
  {
    collection: 'users'
  }
);

// authenticate input against database documents
User.statics.authenticate = ((emailaddress, password, callback) => {
  User.findOne({ emailaddress: emailaddress })
      .exec(function(error, user){
        if(error){
          return callback(error)
        } else if (!user){
          console.log('User not found!');
        }
        bycrypt.compare(password, user.password, function(err, result){
          if(result === true){
            return callback(null, user);
          } else {
            return callback();
          }
        })
      })
});

module.exports = mongoose.model('User', User);

正如您在我的模型上看到的那样,我将 User.statics.authenticate 放在我的代码上以进行一些身份验证。然后在我的 login.js 路由文件上:

const path = require('path');
const express = require('express');
const router = express.Router();
const db = require('../../database/index');
const axios = require('axios');
const User = require('../../database/models/user');

router.get('/', (req, res) => {
  console.log('hi there this is working login get');
});

router.post('/', (req, res) => {
  var emailaddress = req.body.emailaddress;
  var password = req.body.password;


  if( emailaddress && password ){
    User.authenticate(emailaddress, password, function(err, user){
       if(err || !user){
         console.log('Wrong email or password!');
       } else {
         req.session.userId = user._id;
         return res.redirect('/');
       }
    });
  } else {
     console.log('both fields are required...');
  }

});

module.exports = router;

我调用了该函数,然后调用了 User.authenticate 函数,并且我为 root w/c 创建了路由,这是我想要保护并在登录后重定向用户的示例:

router.get('/', (req, res) => {
  if(! req.session.userId ){
    console.log('You are not authorized to view this page!');
  }

  User.findById(req.session.userId)
      .exect((err, user) => {
        if(err){
          console.log(err)
        } else {
          res.redirect('/');
        }
      })
});

在我的反应表单上单击提交时,它会返回此错误:

TypeError: User.findOne is not a function
    at Function.User.statics.authenticate (/Users/mac/Documents/monkeys/database/models/user.js:35:8)

我检查了Mongoose 文档,似乎我使用了正确的语法。知道我在这里做错了什么吗?请帮忙!对不起这里的超级初学者!

附言。我也已经安装并设置了基本的快速会话。

更新:

我从调用中删除箭头函数并使用this.model.findOne,但仍然得到 typerror findOne is not a function

// authenticate input against database documents
User.statics.authenticate = function(emailaddress, password, callback){
  this.model.findOne({ emailaddress: emailaddress })
      .exec(function(error, user){
        if(error){
          return callback(error)
        } else if (!user){
          console.log('User not found!');
        }
        bycrypt.compare(password, user.password, function(err, result){
          if(result === true){
            return callback(null, user);
          } else {
            return callback();
          }
        })
      })
};

【问题讨论】:

  • User 不是猫鼬模型。这是一个“模式”。你想要一个“模型”,即mongoose.mdoel("User", new Schema({ ... }))。全部在文档中。
  • @NeilLunn:你能扩展更多真的需要解决这个问题吗?
  • 而不是使用const User = require('../../database/models/user'); 你可以尝试做:const mongoose = require('mongoose'); const User = mongoose.model('User'); 看看这是否有效?
  • 那么这一行,authenticate:User.findOne({ emailaddress: emailaddress }) 里面的变量“在范围内”当时就是“模式”。对于“静态”,它实际上应该是this.model.findOne(...)。所以this.model 而不是User 这是“模式”。
  • TypeError: 无法读取未定义的属性“findOne”

标签: node.js mongodb reactjs express mongoose


【解决方案1】:

findOne 是您的用户模型上的一个方法,而不是您的用户模型实例。它通过回调将异步结果提供给调用者:

User.findOne({field:'value'}, function(err, doc) { ... });

【讨论】:

  • 如果你看看我的代码,我实际上遵循了这个约定。
猜你喜欢
  • 2016-08-04
  • 1970-01-01
  • 2019-01-18
  • 2016-10-22
  • 2017-10-10
  • 2010-11-05
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多