node.js - 为什么我不能访问 Mongoose 模式的方法?

标签 node.js mongoose 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);

然后我创建了这个路由文件。

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.' });
            };
        });
    });
};

然后我使用 Postman 调用 127.0.0.1:3001/user/isvalid 并提供适当的 Body 内容。终端告诉我 TypeError: User.comparePassword is not a function 并使应用程序崩溃。

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

eta:我最初复制/粘贴失败的模块导出

最佳答案

这将创建实例方法:

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

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

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

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

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

查看文档:

关于node.js - 为什么我不能访问 Mongoose 模式的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42302783/

相关文章:

javascript - 如何一个接一个地依次运行 Gulp 任务

mongodb - 验证 Mongoose 混合架构类型

node.js - Mongoose 在聚合中使用子查询来求和数据

node.js - Mongoose 直接填充创建子文档

node.js - JestJS 测试不会因错误而失败

node.js - bcrypt-nodejs 的未定义函数

node.js - 使用 JWT token 。有更好的方法吗?

javascript - Mongoose:转换为 ObjectId 的值失败

node.js - mongoose#populate 在数组内的嵌套对象中返回 null