【问题标题】:Why can't I access a mongoose schema's method?为什么我不能访问猫鼬模式的方法?
【发布时间】:2017-07-07 06:23:21
【问题描述】:

我在 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 使用适当的 Body 内容调用 127.0.0.1:3001/user/isvalid。终端说告诉我TypeError: User.comparePassword is not a function 并让应用程序崩溃。

自从if (user) 位通过以来,这表明我已经从 Mongo 正确检索了一个文档并拥有一个 User 模式的实例。为什么方法无效?

eta:我原来复制/粘贴失败的模块导出

【问题讨论】:

  • 添加到用户模型模块的末尾:module.exports = mongoose.model('User', UserSchema);
  • @dNitro 我无法复制/粘贴它,但它在我的实际代码中。接得好。编辑添加它

标签: node.js mongoose mongoose-populate


【解决方案1】:

这会创建实例方法:

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

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

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

静态方法是当你想调用它为User.comparePassword()

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

查看文档:

【讨论】:

  • 所以鉴于我提供的代码,传入(user) 应该意味着user.comparePassword() 应该可以工作,但它给出了同样的错误。保持原样并在架构定义中使用UserSchema.statics.comparePassword 确实有效,所以我不怀疑它。我想我只是糊涂了。
猜你喜欢
  • 2017-02-17
  • 1970-01-01
  • 2021-10-01
  • 2017-01-04
  • 1970-01-01
  • 2018-04-27
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多