为什么我不能访问mongoose模式的方法?

The*_*e E 4 mongoose node.js mongoose-populate

我在Nodejs应用程序中有这个Mongoose模式:

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);
Run Code Online (Sandbox Code Playgroud)

我创建了这个路由文件.

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.' });
            };
        });
    });
};
Run Code Online (Sandbox Code Playgroud)

然后,我使用Postman 127.0.0.1:3001/user/isvalid通过适当的Body内容进行调用.终端说告诉我TypeError: User.comparePassword is not a function并崩溃了应用程序.

由于该if (user)位通过,这向我表明我已经从Mongo正确检索了一个文档,并且有一个User模式的实例.为什么方法无效?

eta:模块导出我原本无法复制/粘贴

rsp*_*rsp 7

这创建了实例方法:

UserSchema.methods.comparePassword = function(candidatePassword, targetUser) {
    // ...
};
Run Code Online (Sandbox Code Playgroud)

如果你想要一个静态方法,请使用:

UserSchema.statics.comparePassword = function(candidatePassword, targetUser) {
    // ...
};
Run Code Online (Sandbox Code Playgroud)

静态方法是您想要将其称为User.comparePassword().

实例方法是指您想要将其称为someUser.comparePassword()(在这种情况下,这将非常有意义,因此您不必显式传递用户实例).

查看文档: