【发布时间】:2021-04-27 22:05:48
【问题描述】:
我在猫鼬模型上的 .create 出错了,我无法找出问题所在。我正在使用 Next JS,并且调用发生在 API 路由中......
get 请求工作正常...
pages>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;
}
}
错误信息显示
"这个表达式是不可调用的。
联合类型的每个成员 '{
架构在这里: 模型>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 留在函数调用中,则会出错。
repo 在这里:https://github.com/jondhill333/ProjectManagementTool
感谢您的帮助!
【问题讨论】:
标签: reactjs mongodb typescript mongoose next.js