代码之家  ›  专栏  ›  技术社区  ›  Cameron Hudson

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

  •  0
  • Cameron Hudson  · 技术社区  · 6 年前

    我的问题是我不能对从 findOne() 尽管我 在将同一文档保存到集合之前成功调用同一文档的实例方法。

    首先,通常 require() s、 然后创建架构:

    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 回复  |  直到 6 年前