Home > database >  Type Error when using ObjectId class in MongoDB Node JS Rest API
Type Error when using ObjectId class in MongoDB Node JS Rest API

Time:02-03

I am creating the rest APIs using Next Js and MongoDB, with Type Script checking. When creating one of the routes to fetch the post by Id, I get the following error:

(property) NextApiRequest.query: Partial<{
    [key: string]: string | string[];
}>
Object of query values from url

Argument of type 'string | string[] | undefined' is not assignable to parameter of type 'string | number | ObjectId | ObjectIdLike | Buffer | Uint8Array | undefined'.
  Type 'string[]' is not assignable to type 'string | number | ObjectId | ObjectIdLike | Buffer | Uint8Array | undefined'.
    Type 'string[]' is missing the following properties from type 'Uint8Array': BYTES_PER_ELEMENT, buffer, byteLength, byteOffset, and 3 more.ts(2345)

This is my API Code:

import nc from "next-connect";
import { ObjectId } from "mongodb";

import clientPromise from "../../../../../lib/mongodb";

import type { NextApiRequest, NextApiResponse } from "next";

const one rror = (
  err: any,
  _req: NextApiRequest,
  res: NextApiResponse,
  next: any
) => {
  console.error(err);

  res.status(500).end(err.toString());
  // OR: you may want to continue
  next();
};

const handler = nc({
  one rror,
})
  .get(async (_req: NextApiRequest, res: NextApiResponse) => {
    
    const client = await clientPromise;
    const db = client.db(process.env.MONGO_DB);

    try {
      const _id = new ObjectId(_req.query.postId); // gets the type error here

      const result = await db.collection("posts").findOne({ _id });

      res.json(result);
    } catch (error) {
      console.log("show error", error);
      res.send({
        status: 400,
        message: "Internal Server Error" || error,
      });
    }
  })

I also tried passing default values while destructuring the postId from the _req.query, something like this:

const { postId = '' } = _req.query || { };
const result = await db.collection("posts").findOne({ _id: new ObjectId(postId) }); // gets the type error here as well

But still, the error persists.

The only way the error goes away is if I don't wrap the ID with the new ObjectId class, but then that does not fetch any result from the database. Which is valid in itself. The document id is a type of object id, hence needs to be added.

I am pretty new to the Next Js and API creation using the same framework. Any help to resolve and understand this issue will be appreciated.

CodePudding user response:

ObjectId accepts this type

'string | number | ObjectId | ObjectIdLike | Buffer | Uint8Array | undefined'

however type of query value is : string | string[] | undefined

string[] is not common. try this

const _id = new ObjectId(_req.query.postId as unknown as string);

if you dont want type casting, you could use

let _id;
if (ObjectId.isValid(_req.query.postId)){
     _id = new ObjectId(_req.query.postId);
}
// then if _id exists run the query

if(_id){
    const result = await db.collection("posts").findOne({ _id });
    res.json(result)
}
  • Related