首页 > 解决方案 > 为什么在 Mongoose 模式中声明的方法不起作用

问题描述

所以,这是我的用户模式,我在我用来测试的用户模式上声明了 hello 方法

//user.model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    minlength: 3
  },
  password: { type: String, required: true }
});


UserSchema.methods.hello = () => {
  console.log("hello from method");
};

const User = mongoose.model("User", UserSchema);

module.exports = User;

这是路线文件

//authroutes.js
const router = require("express").Router();
let User = require("../models/user.model");

router.route("/").get((req, res) => {
  res.send("auth route");
});

router.route("/signup").post((req, res) => {
  const username = req.body.username;
  const password = req.body.password;

  const newUser = new User({
    username,
    password
  });

  newUser
    .save()
    .then(() => res.json(`${username} added`))
    .catch(err => console.log(err));
});

router.route("/login").post(async (req, res) => {
  await User.find({ username: req.body.username }, function(err, user) {
    if (err) throw err;

    //this doesnt work
    user.hello();
    res.end();
  });
});

module.exports = router;

在登录路径中,我调用 hello 函数进行测试,但这不起作用并引发此错误

类型错误:user.hello 不是函数

标签: node.jsmongoosemongoose-schemabcrypt

解决方案


您需要使用User.findOne而不是User.find,因为 find 返回一个数组,但我们需要的是模型的一个实例。

此外,不应使用 ES6 箭头函数声明实例方法。箭头函数明确阻止绑定 this,因此您的方法将无权访问文档并且它将不起作用。

所以你最好更新这样的方法:

UserSchema.methods.hello = function() {
  console.log("hello from method");
};

推荐阅读