reactjs - .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
任何帮助都感激不尽!
解决方案
修复它......发布请求需要更新如下:
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 });
}
推荐阅读
- android - 如何在 nativescript 应用程序中捕获 android dispatchKeyEvent?
- python-3.x - 如何在python所有脚本上循环?
- c# - ComboBox.SelectedValue 在表单的构造函数中为 null
- r - 使用 dplyr 删除至少一个 NA 的所有行的 R 函数不起作用
- python - 在 While 循环中创建停止 - Python
- pytorch - 如何从 pytorch 模块获取子模块序列?
- karate - 空手道 - 访问请求的变量就像响应一样
- ios - Flutter iOS 应用程序被拒绝,因为“NSLocationAlwaysUsageDescription”没有目的字符串,但该应用程序不使用位置服务
- html - 使用引导程序创建水平导航栏
- javascript - 如何使堆叠的多个div的宽度动态调整为其中最长的内容?