node.js - 为什么在 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 不是函数
解决方案
您需要使用User.findOne
而不是User.find
,因为 find 返回一个数组,但我们需要的是模型的一个实例。
此外,不应使用 ES6 箭头函数声明实例方法。箭头函数明确阻止绑定 this,因此您的方法将无权访问文档并且它将不起作用。
所以你最好更新这样的方法:
UserSchema.methods.hello = function() {
console.log("hello from method");
};
推荐阅读
- vue.js - 是否可以在屏幕外渲染 vue 组件并转换为图像?
- sql - SQL脚本中的分号问题
- powershell - 为什么 TeamCity 的 PowerShell Build Runner 显示堆栈跟踪而不是错误输出?
- r - 波士顿住房数据使用 R 的均方根误差 (RMSE):
- selenium-webdriver - 将 xunit 功能测试结果发布到 Azure devops
- javascript - 使用 d3 v5 创建图形网络:生成节点之间的链接/边时出错
- c# - 如何在 Kubernetes 中动态创建参数化的 Pod
- r - R - write.csv 将字符字段中的某些值导出为 NULL
- r - 如何在 R 中使用 k-fold CV 手动训练数据?
- android - 在android模拟器中禁用传感器