首页 > 解决方案 > 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);

标签: node.jsmongoosemongoose-schema

解决方案


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


推荐阅读