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

113
Vistas
Getting Null From MongoDB

Why my Code Giving me Null

async function run() {
  try {
    await client.connect();

    const productsCollection = client.db("inventory").collection("items");

    // Get All Products
    app.get('/products', async (req, res) => {
      const query = {};
      const cursor = productsCollection.find(query);
      const products = await cursor.toArray();
      res.send(products);
    });

    // Get Single Product
    app.get('/products/:id', async (req, res) => {
      const id = req.params.id;
      console.log(id);
      const query = {_id: ObjectId(id)};
      const product = await productsCollection.findOne(query);
      res.send(product);
    })
  } 
  finally {
    
  }
}
run().catch(console.dir);

I do not understand why Null is showing? And there is no error in giving products /id And It doesn't even showing anything And this error is showing in the front end console Uncaught (in promise) SyntaxError: Unexpected end of JSON input

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

0

In mongo, you should use await on every event that is related to the database. this is because it takes time to actually retrieve the data from the collection and the javascript code will not wait unless you tell it to.

in your example

const cursor = productsCollection.find(query);

should be

const cursor = await productsCollection.find(query);

this is my first note

My second note is to share your frontend code and I will edit the answer if there is any thing to add

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