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

Node.js 为什么Mongoose模式中声明的方法不起作用,node.js,mongoose,mongoose-schema,bcrypt,Node.js,Mongoose,Mongoose Schema,Bcrypt,所以,这里是我的用户模式,我在其中声明了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, min

所以,这里是我的用户模式,我在其中声明了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不是函数


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

也不应使用ES6箭头函数声明。 箭头函数显式阻止绑定,因此您的方法将无法访问文档,并且无法工作

因此,您最好更新如下方法:

UserSchema.methods.hello=function(){
log(“来自方法的你好”);
};

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

也不应使用ES6箭头函数声明。 箭头函数显式阻止绑定,因此您的方法将无法访问文档,并且无法工作

因此,您最好更新如下方法:

UserSchema.methods.hello=function(){
log(“来自方法的你好”);
};

你在用户变量中得到了什么??@pu this`[{u id:5e32c0e7d2a08d6c10768089,用户名:'rohit',密码:'$2b$10$RQir9GkQL/a604qwh3c5foanfj20dpuuuuuuu7pn/IIsVNLzCdb.j7lVim','u v:0}]`你在用户变量中得到了什么??@pu this`[{id:5e32c0e7d2a08d6c10768089,用户名:'rohit',密码:'2b$10$RQir9GkQL/A604QwH3c5fOANFJ20DpUU7pn/IIsVNLzCdb.j7lVim','`不,它不起作用,你能看看这张图片,这样你就可以有一个想法吗,我的发帖要求是这张不起作用,你能看看这张图片,这样你就可以有一个想法吗,我的发帖要求是这张