Category Schema
import mongoose, { InferSchemaType, Model, model, Schema, Types, models } from "mongoose";
import type { Course } from "./course.model";
export type Category = InferSchemaType<typeof categorySchema> & {_id: Types.ObjectId;};
export const category = {model: "Category",collection: "categorys",} as const;
const categorySchema = new Schema({
name: { type: String, unique: true },
courses: [{ type: Schema.Types.ObjectId, ref: 'Course' }],
},{
collection: category.collection, timestamps: true
});
categorySchema.index({ name: 1 });
const CategoryModel: Model<Category> =models?.[category.model] || model<Category>(category.model, categorySchema);
export default CategoryModel;
PATCH route :
import { currentUser } from "@/lib/auth";
import CategoryModel from "@/models/category.model";
import CourseModel from "@/models/course.model";
import { NextResponse } from "next/server"; import {Mongoose} from "mongoose";
export async function PATCH( req: Request, { params }: { params: { courseId: string } } ) { try { const session = await currentUser(); const { courseId } = params;
const values = await req.json();
console.log(values.categoryId);
if (!session) {
return new NextResponse("Unauthorized", { status: 401 });
}
const course = await CourseModel.findById({
_id: courseId || params.courseId,
});
console.log(course?.id);
const selectedCategoryId = values.categoryId;
const initialCategoryId = course?.categoryId;
if (selectedCategoryId !== initialCategoryId) {
await Promise.all([
await CourseModel.findByIdAndUpdate(
{
_id: courseId || params.courseId,
userId: session.id,
},
{ $set: { ...values } },
{ new: true }
),
await CategoryModel.findByIdAndUpdate(
{
_id: initialCategoryId,
},
{ $pull: { courses: course?._id } },
{ new: true }
),
await CategoryModel.findByIdAndUpdate(
{
_id: selectedCategoryId,
},
{ $push: { courses: courseId } },
{ new: true }
),
]);
return NextResponse.json("Updated");
}
return NextResponse.json("Not Updated");
}
catch (error)
{console.error("[Courses]", error);return new NextResponse("Internal Error", { status: 500 });}}
i want to add courseId or course?._id into courses array in category Schema
I tried mongoose.Types.ObjectId, but all the methods i have used are creating new objectId instead of adding the course id into courses array, i am seding course id as params to the patch request, please help me with this, do i need change the schema or is it fine?, if i change the array into array of strings, the issue might get solved but i want to have a relation between course and category schema
Karthikeya mojjada is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.