首页 > 解决方案 > 邮递员:TypeError:User.findOne 不是函数

问题描述

邮递员:TypeError:User.findOne不是函数

嗨,我正在尝试在讲座结束时运行 POST 请求,但出现此错误。

我认为问题出在User.findOne方法上。

我的代码如下:

//users.js


const express = require('express');
const router = express.Router();
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');

// Load User Model
const User = require('../../models/User');

//@route GET api/users/test
//@description Test users route
//@access Public

router.get('/test', (req, res) => res.json({
  msg: 'Users Works'
}));

//@route GET api/users/register
//@description Register a user
//@access Public

router.post('/register', (req, res) => {
  User.findOne({
    email: req.body.email
  }).then(user => {
    if (user) {
      return res.status(400).json({
        email: 'Email already exists'
      });
    } else {

      const avatar = gravatar.url(req.body.email, {
        s: '200',
        r: 'pg',
        d: 'mm'
      });

      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        avatar,
        password: req.body.password
      });

      // encryption of password, throw and catch of error
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));

        });
      });
    }
  });
});

module.exports = router

标签: javascriptmethods

解决方案


推荐阅读