I am working in a NextJs project with mongoDB. When I am submitting a form its showing me this error…
events validation failed: user: Cast to ObjectId failed for value “{ success: true, data: { _id: ‘66d617672c64115d9df381f9’, firstName: ‘aaa aaa’, email: ‘aaaa@gmail.com’, isActive: true, isAdmin: true, clerkUserID: ‘user_2lWrZ1KjGMhfMiPsu9G8Qisn7jj’, createdAt: ‘2024-09-02T19:52:07.123Z’, updatedAt: ‘2024-09-02T19:52:07.123Z’, __v: 0 } }” (type Object) at path “user” because of “BSONError”
my event schema
import mongoose from "mongoose";
const eventSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
organizer: {
type: String,
required: true,
},
guests: {
type: Array,
required: true,
},
location: {
type: String,
required: true,
},
date: {
type: String,
required: true,
},
time: {
type: String,
required: true,
},
images: {
type: Array,
required: true,
},
ticketTypes: {
type: Array,
required: true,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "users",
required: true,
},
},
{ timestamps: true }
);
// define the Event model with the schema
if (mongoose.models && mongoose.models.events) {
delete mongoose.models.events;
}
const EventModel = mongoose.model("events", eventSchema);
export default EventModel;
this is user-schema
import mongoose from "mongoose";
const userSchema = new mongoose.Schema(
{
firstName: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
isActive: {
type: Boolean,
default: true,
},
isAdmin: {
type: Boolean,
default: false,
},
clerkUserID: {
type: String,
required: true,
unique: true,
},
},
{ timestamps: true }
);
// check if user model is already exists
if (mongoose.models && mongoose.models["users"]) {
delete mongoose.models["users"];
}
const UserModel = mongoose.model("users", userSchema);
export default UserModel;
function i’m using
import { connectMongoDB } from "@/config/dbConfig";
import UserModel from "@/models/user-model";
import { auth } from "@clerk/nextjs/server";
import { NextRequest, NextResponse } from "next/server";
connectMongoDB();
export async function GET(request: NextRequest) {
try {
const { userId } = auth();
if (!userId) throw new Error("Unauthorized request");
const userInMongoDB = await UserModel.findOne({ clerkUserID: userId });
return NextResponse.json({ user: userInMongoDB }, { status: 200 });
} catch (error: any) {
return NextResponse.json({ message: error.message }, { status: 500 });
}
}
now let me know, how can I resolve this!!!