首页 > 解决方案 > .create() on mongoose 模式错误,“此表达式不可调用”-TypeScript

问题描述

我在猫鼬模型上的 .create 出错了,我无法找出问题所在。我正在使用 Next JS,并且调用发生在 API 路由中......

获取请求工作正常...

页面>API>task.tsx

import dbConnect from "../../util/dbconnect";
import Task from "../../models/Task";

dbConnect();

export default async function (req, res) {
  const { method } = req;
  switch (method) {
    case "GET":
      try {
        const tasks = await Task.find({});
        res.status(200).json({ success: true, data: tasks });
      } catch (error) {
        res.status(400).json({ success: false });
      }
      break;
    case "POST":
      try {
        const task = await Task.create(req.body);
        res.status(201).json({ success: true, data: task });
      } catch (error) {
        res.status(400).json({ success: false });
      }
      break;
    default:
      res.status(400).json({ success: false });
      break;
  }
}

错误消息显示

"此表达式不可调用。联合类型的每个成员 '{ <DocContents = ITask | _AllowStringsForIds<Pick<Pick<_LeanDocument, "_id" | "__v" | "id" | "title" | "description" | "createdDate " | "estimatedDueDate" | "status">, "_id" | ... 6 更多 ... | "status">>>(doc: DocContents): Promise<...>; <DocContents = ITask | _AllowStringsForIds< ...>>(docs: DocContents[], opt...' 有签名,但这些签名都不兼容。ts(2349) "

架构在这里:models>Task.tsx

import mongoose, { Schema, Document, model, models } from "mongoose";

export interface ITask extends Document {
  title: string;
  description: string;
  createdDate: string;
  estimatedDueDate?: string;
  status: string[];
}

const TaskSchema: Schema = new Schema({
  title: {
    type: String,
    required: [true, "Please add a title"],
    unique: true,
    trim: true,
    maxlength: [60, "Title cannot be more than 60 Characters "],
  },
  description: {
    type: String,
    required: [true, "Please add a title"],
    unique: true,
    trim: true,
    maxlength: [400, "Title cannot be more than 60 Characters"],
  },
  createdDate: {
    type: Date,
    required: [true],
  },
  estimatedDueDate: {
    type: Date,
    required: [
      false,
      "Entering a due date helps to create your visual timeline",
    ],
  },
  status: {
    type: String,
    required: [true],
    default: "New",
  },
});

export default models.Task || model<ITask>("Task", TaskSchema);

我试图将 .create() 更改为 await new Task(req.body) - 如果我将 req.body 排除在外,那么该帖子将使用一个空的新文档(该文档没有指定的所有属性) Schema)如果我将 req.body 留在函数调用中,那么它会出错。

回购在这里: https ://github.com/jondhill333/ProjectManagementTool

任何帮助都感激不尽!

标签: reactjsmongodbtypescriptmongoosenext.js

解决方案


修复它......发布请求需要更新如下:

 case "POST":
      try {
        const task = await new Task(req.body);
        res.status(201).json({ success: true, data: task });
        task.save();
      } catch (error) {
        res
          .status(400)
          .json({ success: false + " post", message: error.message, error });
      }

推荐阅读