Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

342
Vistas
How to remove new ObjectId() from the display of JSON data?

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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;
    
 }

about 4 years ago · Juan Pablo Isaza Denunciar

0

res._id = res._id.str;
return res;

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda