node.js - schema.methods 不是函数
问题描述
我一直在尝试在猫鼬中的用户模式上创建一个方法,但是它一直说方法不是函数,我不知道为什么。我对 mongoose 和 express 还很陌生,而且我很确定我目前已经设置了我的文件,所以我不知道是什么导致了这个问题。作为最后一次尝试,我尝试切换到箭头函数,但这也不起作用。
用户路由文件
const router = require("express").Router();
let user = require("../models/user_model");
const Joi = require("@hapi/joi");
// GET dreams
// POST dreams
// DELETE dreams
// UPDATE dreams
router.route("/").get((req, res) => {
console.log(user.addType());
res.send("hello this is a users page");
});
用户模型文件
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true,
trim: true,
min: 3
},
password: {
type: String,
trim: true,
required: true,
min: 6
}
},
{
timestamps: true
}
);
userSchema.methods.addTypes = function() {
console.log("woof");
};
userSchema.methods.joiValidate = data => {
let Joi = require("@hapi/joi");
const schema = {
username: Joi.string()
.min(6)
.required(),
password: Joi.string()
.min(6)
.required()
};
return schema.validate(data);
};
module.exports = mongoose.model("User", userSchema);
解决方案
UPDATE! Other than having typo on your code, you also need to create an instance of your model ('user'). You cannot just call the function of the model.
let user = new user({ // Create an instance first
username: 'Tester',
password: '12345678'
})
console.log(user.addType())
you declared
addTypes()
Cheers
推荐阅读
- javascript - HTML Figure 标签用法
- javascript - 关于通过 CSS 使用或不使用 JavaScript 辅助实现具有多个选项卡的单个 HTML 页面
- performance - haskell 列表推导是懒惰的吗?
- apache-kafka - Salesforce Camel Kafka 连接器将消息转换为奇怪的格式
- java - 使用 Java 8 Streams 将迭代方法转换为函数式
- mysql - 从 SQL 查询 recipesexample 数据库,只为凡人
- flutter - “您可能在 Ruby 解释器或扩展库中遇到了错误。” 使用颤振在 iOS 模拟器上运行应用程序时出错
- python - 如何在使用 torch 模块的 iOS 或 android 上运行 python 脚本?
- macos - 在mac 64位上的nasm程序集中删除/取消链接文件
- python - 如何在 Python 字典的字典中引用?