Reputation: 11
My .create on a mongoose model is erroring and I cannot find out what the issue is. I'm using Next JS and the call is happening in an API route....
The get request works fine...
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;
}
}
THe error message reads
"This expression is not callable. Each member of the union type '{ <DocContents = ITask | _AllowStringsForIds<Pick<Pick<_LeanDocument, "_id" | "__v" | "id" | "title" | "description" | "createdDate" | "estimatedDueDate" | "status">, "_id" | ... 6 more ... | "status">>>(doc: DocContents): Promise<...>; <DocContents = ITask | _AllowStringsForIds<...>>(docs: DocContents[], opt...' has signatures, but none of those signatures are compatible with each other.ts(2349) "
The Schema is here: 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);
I have tried to change the .create() to await new Task(req.body) - if I leave the req.body out, then the post works with an empty new document (which doesn't have all of the properties specified in the Schema) if I leave req.body in the function call then it errors.
the repo is here: https://github.com/jondhill333/ProjectManagementTool
Any help gratefully recieved!
Upvotes: 0
Views: 726
Reputation: 11
fixed it ... the post request needs to updated as below:
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 });
}
Upvotes: 1