While developing the backend of my app, I have integrated mongoose and Next.js. My current challenge is implementing a push function to add a new user to the database. As I am still relatively new to using mongoose, especially with typescript, I am following the documentation as closely as possible. In my schema setup, I have Users as the main document and Donations as a subdocument under Users. Specifically for my post request, my goal is to create a user with an empty donations array.
//users.ts
import mongoose, { Model, Schema, Types } from "mongoose";
interface IItem {
name: string;
condition: "poor" | "fair" | "good" | "very good";
}
// Subdocument Interface
interface IDonation {
date: Date;
address: string;
items: Types.Array<IItem>;
}
// Document Interface
interface IUser {
firstName: string;
lastName: string;
email: string;
password: string;
donations: IDonation[];
}
type UserDocumentProps = {
donations: Types.DocumentArray<IDonation>;
};
type UserModelType = Model<IUser, {}, UserDocumentProps>;
// Create Model
// If already created, don't create again
export const User =
mongoose.models.User ||
mongoose.model<IUser, UserModelType>(
"User",
new Schema<IUser, UserModelType>(
{
firstName: String,
lastName: String,
email: String,
password: String,
donations: [
new Schema<IDonation>({
date: Date,
address: String,
items: [{ name: String, condition: String }],
}),
],
},
{
timestamps: true,
}
)
);
// api/users/route.ts
import { NextRequest, NextResponse } from "next/server";
import connectMongoDB from "../../../libs/mongodb";
import { User } from "../../../models/users";
import mongoose from "mongoose";
export async function POST(request: NextRequest) {
const { firstName, lastName, email, password } = await request.json()
console.log(firstName, lastName, email, password); // prints values
if (mongoose.connection.readyState === 0) await connectMongoDB(); // if already connected, don't make new connection
await User.create({ firstName, lastName, email, password }); // error occurs here
return NextResponse.json({ message: "User Created" }, { status: 201 });
}
https://i.stack.imgur.com/i7kNW.png
Although I am successfully retrieving values from the json request, I encounter an issue when attempting to execute User.create({ request values }). This process is carried out using Postman for API requests. Any insights into potential issues related to users.ts would be greatly appreciated.