-1

How do I remove the new ObjectId() from my output when displaying JSON data?

Below is my code to get the data using the id from mongodb:

 async get(id) {
    if (!id) throw 'You must provide an id to search for';

    const restaurantsCollection = await restaurants();
    const res = await restaurantsCollection.findOne({ _id: id });
    if (res === null) throw 'No restaurant with that id';

    return res;

The output is:

{
  _id: new ObjectId("6157530bbba1dbb9f7e68e4a"),
  name: 'The Saffron Lounge',
  location: 'New York City, New York',
  phoneNumber: '123-456-7890',
  website: 'http://www.saffronlounge.com',
  priceRange: '$$$$',
  cuisines: [ 'Cuban', 'Italian' ],
  overallRating: 3,
  serviceOptions: { dineIn: true, takeOut: true, delivery: false }
}

The output I want is:

{
  _id: "6157530bbba1dbb9f7e68e4a",
  name: 'The Saffron Lounge',
  location: 'New York City, New York',
  phoneNumber: '123-456-7890',
  website: 'http://www.saffronlounge.com',
  priceRange: '$$$$',
  cuisines: [ 'Cuban', 'Italian' ],
  overallRating: 3,
  serviceOptions: { dineIn: true, takeOut: true, delivery: false }
}

Do I use ObjectId.toString()? Not sure where to use this either

Swayam Shah
  • 200
  • 1
  • 12

3 Answers3

2

According to this https://docs.mongodb.com/manual/reference/method/ObjectId.toString/ ObjectId.toString() will give you a string that still contains the ObjectId("...") part. You could use a regex to remove that.

async get(id) {
    if (!id) throw 'You must provide an id to search for';

    const restaurantsCollection = await restaurants();
    const res = await restaurantsCollection.findOne({ _id: id });
    
    if (res === null) throw 'No restaurant with that id';
    res._id = res._id.toString().replace(/ObjectId\("(.*)"\)/, "$1")
    return res;
    
 }
mmoehrlein
  • 164
  • 9
2
res._id = res._id.str;
return res;

https://docs.mongodb.com/manual/reference/method/ObjectId/

0

I faced a similar issue when receiving a string array from MongoDb (it was necessary to send it without parsing due to abstract logic on the backend).

In my case I had lots of objects inside this string array with ObjectId as the value of the id prop e.g.:

"[{'id': ObjectId(id)}, // many others]"

My solution was to write a recursive function to get the index of each 'ObjectId' string and then remove it using JS substring method.

I'll leave it here for reference in case someone needs:

function removeObjId(str){
  const objIdLen = 9;
  const objIdInd = str.search("ObjectId");
 
  if(objIdInd == -1) return str;
  
  const objIdEndInd = objIdInd + objIdLen
  const valueInd  = str.substring(objIdEndInd)
  const commaInd = valueInd.indexOf(",")
   
const nStr = 
    str.substring(-1, ind-1)
    +   "'"
 + str.substring(objIdEndInd, objIdEndInd + commaInd -1)
    + "'"
    + str.substring(commaInd + objIdEndInd)
    
    
    return removeObjId(nStr)}
Felipe
  • 196
  • 2
  • 6