如何解决猫鼬模型静态错误

时间:2020-03-27 05:11:22

标签: node.js mongodb mongoose graphql

我为graphql API定义了以下模型:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const Post = Schema({
  _id: Schema.Types.ObjectId,
  title: { type: String, required: true },
  description: { type: String, required: true },
  content: { type: String, required: true },
  comments: { type: [String], required: true },
  tags: { type: [String], required: true },
  stats: { type: [Number], required: true },
  datePublished: { type: Date, required: true },
  dateUpdated: { type: Date, required: true }
});

// TODO: Implement methods here
// Post.statics.getPost = function(args) {
//   console.log(this.title);
//   return this.model
// };

Post.statics.getPost = function(args) {
  this.find({});
};
module.exports = mongoose.model("Post", Post, "posts");

我愿意在模型中创建一个函数以从数据库中获取信息。但是,当我请求此功能的API时,会收到以下响应,这是一个错误。我还尝试将this更改为Post失败。

{
  "errors": [
    {
      "message": "this.find is not a function",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "getPost"
      ]
    }
  ],
  "data": null
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您似乎没有实例化猫鼬模式的实例。您需要使用new。这将为您提供参考。

const Post = new mongoose.Schema({ ...