为什么在Mongoose模式中声明的方法不起作用

问题描述 投票:0回答:1

所以,这是我的用户架构,在该架构中我向用来测试的Userschema声明了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函数进行测试,但这无法正常工作并引发此错误

TypeError:user.hello不是函数

node.js mongoose mongoose-schema bcrypt
1个回答
0
投票
Instance methods不应使用ES6箭头函数声明。箭头函数明确阻止了此绑定,因此您的方法将无权访问文档,并且将无法使用。

所以您需要这样的更新方法:

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

© www.soinside.com 2019 - 2024. All rights reserved.