2017-02-17 63 views
2

我有一個應用程序的NodeJS這貓鼬模式:爲什麼我不能訪問貓鼬模式的方法?

const mongoose = require('mongoose'), 
    Schema = mongoose.Schema, 
    sodium = require('sodium').api; 

const UserSchema = new Schema({ 
    username: { 
     type: String, 
     required: true, 
     index: { unique: true } 
    }, 
    salt: { 
     type: String, 
     required: false 
    }, 
    password: { 
     type: String, 
     required: true 
    } 
}); 

UserSchema.methods.comparePassword = function(candidatePassword, targetUser) { 
    let saltedCandidate = candidatePassword + targetUser.salt; 
    if (sodium.crypto_pwhash_str_verify(saltedCandidate, targetUser.password)) { 
     return true; 
    }; 
    return false; 
}; 

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

而且我創造了這個路線文件。

const _ = require('lodash'); 
const User = require('../models/user.js'); // yes, this is the correct location 

module.exports = function(app) { 
    app.post('/user/isvalid', function(req, res) { 
     User.find({ username: req.body.username }, function(err, user) { 
      if (err) { 
       res.json({ info: 'that user name or password is invalid. Maybe both.' }); 
      }; 
      if (user) { 
       if (User.comparePassword(req.body.password, user)) { 
        // user login 
        res.json({ info: 'login successful' }); 
       }; 
       // login fail 
       res.json({ info: 'that user name or password is invalid Maybe both.' }); 
      } else { 
       res.json({ info: 'that user name or password is invalid. Maybe both.' }); 
      }; 
     }); 
    }); 
}; 

然後,我使用郵遞員撥打127.0.0.1:3001/user/isvalid與適當的身體內容。終端說告訴我TypeError: User.comparePassword is not a function並崩潰的應用程序。

由於if (user)位通過,這表明我已經從Mongo中正確檢索了一個文檔並擁有User模式的實例。爲什麼該方法無效?

ETA:模塊出口我無法複製/粘貼最初

+1

添加到最終用戶模型模塊的:'module.exports = mongoose.model( '用戶',UserSchema);' – dNitro

+0

@dNitro我未能複製/粘貼,但它在我的實際代碼。接得好。編輯添加它 –

回答

4

這將創建實例方法:

UserSchema.methods.comparePassword = function(candidatePassword, targetUser) { 
    // ... 
}; 

如果你想有一個靜態方法使用這樣的:

UserSchema.statics.comparePassword = function(candidatePassword, targetUser) { 
    // ... 
}; 

靜態方法當你想把它稱爲User.comparePassword()

實例方法是當你想把它稱爲someUser.comparePassword()(在這種情況下會產生很多意義,這樣你就不必顯式地傳遞用戶實例)。

參見文檔:

+0

因此給出我提供的代碼,傳遞'(用戶)'應該意味着'user.comparePassword()'應該工作,但它會給出相同的錯誤。 保持原樣並在模式定義中使用'UserSchema.statics.comparePassword'確實可行,所以我並不懷疑它。我猜,我只是感到困惑。 –