未为Mongoose findOne()查询结果定义的实例方法?

时间:2018-06-28 23:33:11

标签: node.js mongodb mongoose

我的问题是,即使我可以之前成功在同一文档上调用实例方法,也无法在从findOne()查询返回的文档上调用模型实例方法。我将其保存到集合中。

首先,通常使用require(),然后创建架构:

var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const pwHash = require('password-hash');
const dbAddress = 'mongodb://localhost/18-652_Ramp_Up_Project';
const projectDb = mongoose.createConnection(dbAddress);

const exampleUserSchema = new mongoose.Schema({
  username: String,
  password: String,
});

// Instance methods of the User class:
exampleUserSchema.methods.checkPw = function(pwToAuthenticate) {
  return pwHash.verify(pwToAuthenticate, this.password);
};

// Retrieve the document corresponding to the specified username.
exampleUserSchema.statics.findOneByUsername = function(username) {
  return new Promise((resolve, reject) => {
    projectDb.collection('exampleUsers').findOne(
      {username: username},
      (err, existingUser) => {
        if (err) throw(err);
        return resolve(existingUser ? existingUser : null);
      }
    );
  });
};

// Constructor (through mongo);
const ExampleUser = projectDb.model('ExampleUser', exampleUserSchema, 'exampleUsers');

现在有趣的部分:我可以创建一个新用户并成功调用实例方法:

// Create a test user and try out the 
const hashedPw = pwHash.generate('fakePassword');
ExampleUser.create({username: 'fakeUsername', password: hashedPw}, (err, newUser) => {
  console.log(newUser.checkPw('fakePassword')); // --> true
  console.log(newUser.checkPw('password123')); // --> false
  newUser.save((err) => {
    console.log('New user ' + newUser.username + ' saved.'); // --> New user fakeUsername saved.
  });
});

但是当我尝试在从findOne()查询返回的文档上调用它时,它是“不是函数”:

/* POST user login info. */
router.post('/login', (req, res, next) => {

  // Try to look up the user in the database.
  ExampleUser.findOneByUsername(req.body.username) // Static method works.
      .then((existingUser) => {
        console.log(existingUser);
        if (existingUser && existingUser.checkPw(req.body.password)) { // Instance method doesn't.
          console.log('Access granted.');
        } else {
          console.log('Access denied.');
        }
      });
});

module.exports = router;

这将产生:

POST /example/login 200 22.587 ms - 14
{ _id: 5b3d592d8cd2ab9e27915380,
  username: 'fakeUsername',
  password: 'sha1$ea496f95$1$6a01df977cf204357444e263861041c622d816b6',
  __v: 0 }
(node:40491) UnhandledPromiseRejectionWarning: TypeError: existingUser.checkPw is not a function
    at ExampleUser.findOneByUsername.then (/Users/cameronhudson/Documents/GitHub/18-652_Ramp_Up_Project/routes/exampleUsers.js:52:42)
    at process._tickCallback (internal/process/next_tick.js:68:7)

0 个答案:

没有答案