Get data with types from mongodb in Nextjs

Hi everyone, I have nextjs project where I use MongoDB to get data, so when I fetch data I want to get types, I show you what result I want to get.

please consider that, I want such an array because I want to know what type of data is coming, when I get “_id”, “typeof” gives me “String” (I know why it doing such), and I want to get that _id is a “ObjectId”, and so on

for example:

 [
{
_id: '323030049934bwd', 
type: ObjectId
},{
name: "David", 
type: String
},{
active: false, 
type: boolean
}
]

I hope I did to describe my situation,

The mongodb equivalent is $type.

sorry for the late answer, but, I use Nextjs, how I can use $type?

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

export default async function handler(req, res) {
  const client = await clientPromise;
  try {
    await client.connect();

    const allData = await client
      .db()
      .collection(req.query.collection[0])
      .find({})
      .toArray();

    return res.send(allData);
  } finally {
    await client.close();
  }
}

I know that you

that is in the title of the post.

But using $type (please click on the link and look at the examples) is a server thing. It has nothing to do with nextjs or what ever client you are using.

I just found out the following which might be a better solution

1 Like