CastError: Cast to ObjectId failed for value "{ _id: undefined }

28 Views Asked by At

This is my Schema-

import mongoose from 'mongoose';

// Define the schema based on the ProductType interface
const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  category: {
    type: String,
  },
  image: {
    type: String,
  },
  sku: {
    type: String,
  },
  stock: {
    type: Number,
  },
  price: {
    type: String,
  },
  status: {
    type: String,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  updatedAt: {
    type: Date,
    default: Date.now,
  },
});

// Create the Mongoose model
const Product =
  mongoose.models.products || mongoose.model('products', productSchema);

export default Product;

and this is my api code to Update and Fetch data using product id

import { NextResponse } from 'next/server';
import connectDB from '@/utils/db';
import Product from '@/utils/models/product/product';

export async function PUT(request: any, content: any) {
  //extracting the id
  const productId = content.params.id;
  const filter = { _id: productId };

  // takin the input to update
  const payload = await request.json();
  console.log(payload);

  // Connect to the MongoDB database
  await connectDB();

  const result = await Product.findOneAndUpdate(filter, payload);
  console.log(`Product with id: ${productId} updated`);
  return NextResponse.json({ result, success: true });
}

// Define the GET request handler to fetch a product by its ID

export async function GET(request: any) {
  //extracting the id
  const productId = request.params?.id;
  console.log(request.params);
  const record = { _id: productId };
  console.log(productId);

  // Connect to the MongoDB database
  await connectDB();

  const data = await Product.findById(record);
  console.log(`Product with id: ${productId} fetched`);
  return NextResponse.json({ data, success: true });
}

so when I try to update the data with this api the data is getting updated and also the product data is getting printed but when I use GET to fetch only the data of the product by using the same id which is used for updating details it is giving me error-

" ⨯ CastError: Cast to ObjectId failed for value "{ _id: undefined }" (type Object) at path "_id" for model "products" at SchemaObjectId.cast (E:\Official\mongo based new\node_modules\mongoose\lib\schema\objectId.js:250:11) at SchemaType.applySetters (E:\Official\mongo based new\node_modules\mongoose\lib\schemaType.js:1221:12) at SchemaType.castForQuery (E:\Official\mongo based new\node_modules\mongoose\lib\schemaType.js:1636:17) at cast (E:\Official\mongo based new\node_modules\mongoose\lib\cast.js:304:34) at Query.cast (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:4775:12) at Query._castConditions (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:2199:10) at model.Query._findOne (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:2513:8) at model.Query.exec (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:4319:80) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async GET (webpack-internal:///(rsc)/./src/app/api/products/edit/[id]/route.ts:41:18) at async E:\Official\mongo based new\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:61856 { stringValue: '"{ _id: undefined }"', messageFormat: undefined, kind: 'ObjectId', value: { _id: undefined }, path: '_id', reason: BSONError: input must be a 24 character hex string, 12 byte Uint8Array, or an integer at new ObjectId (E:\Official\mongo based new\node_modules\bson\lib\bson.cjs:2147:23) at castObjectId (E:\Official\mongo based new\node_modules\mongoose\lib\cast\objectid.js:25:12) at SchemaObjectId.cast (E:\Official\mongo based new\node_modules\mongoose\lib\schema\objectId.js:248:12) at SchemaType.applySetters (E:\Official\mongo based new\node_modules\mongoose\lib\schemaType.js:1221:12) at SchemaType.castForQuery (E:\Official\mongo based new\node_modules\mongoose\lib\schemaType.js:1636:17) at cast (E:\Official\mongo based new\node_modules\mongoose\lib\cast.js:304:34) at Query.cast (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:4775:12) at Query._castConditions (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:2199:10) at model.Query._findOne (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:2513:8) at model.Query.exec (E:\Official\mongo based new\node_modules\mongoose\lib\query.js:4319:80) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async GET (webpack-internal:///(rsc)/./src/app/api/products/edit/[id]/route.ts:41:18) at async E:\Official\mongo based new\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:61856, valueType: 'Object', model: Model { products } }"

and if I use Product.findOne(record) instead of Product.findById(record); this is the output"

"undefined undefined MongoDB connection successful Product with id: undefined fetched

{ "data": null, "success": true } "

0

There are 0 best solutions below