Home > other >  Mongoose returns "new ObjectId" in _id field of the result
Mongoose returns "new ObjectId" in _id field of the result

Time:10-12

When I try to query, the result contains the _id field with "new ObjectId()" in it. How to avoid this "new ObjectId()" and only include the hash value as string. Because of this issue, sending the data back as JSON response is failing.

The following is a basic demo:

My code for querying:

book_data = await Book.find({ slug: 'test' }).
                        where('status').equals('Active').select('title').exec()

console.log( book_data )                    

Response:

[
  {
    _id: new ObjectId("6164aff742da0eac31a87b9a"),
    title: 'Test' 
  }
]

CodePudding user response:

You can pass in an options object to the .find method. There, you can specify the field you want to ignore by providing a 0 as the value.

See here for more info as well.

Something like this should do the trick:

book_data = await Book.find(
    { slug: 'test' }, // Query
    { _id: 0 }        // Options
).where('status').equals('Active').select('title').exec();

While the above query should do the trick, I believe this means you could also just do:

book_data = await Book.find(
    // Query
    { slug: 'test', status: 'Active' },
    // Options
    { _id: 0, title: 1 }                
).exec();

Edit 2

I found a better way to do this via .find..

Mongo Playground

This is what your code would look like:

book_data = await Book.find({
  slug: "test",
  status: "active"
},
{
  title: 1,
  _id: {
    "$toString": "$_id"
  }
}).exec();
  • Related