Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!