A
A
Alexander2021-07-29 14:48:14
MongoDB
Alexander, 2021-07-29 14:48:14

How to return data from Mongodb to the frontend?

How to return data from Mongodb to the frontend?

const db = client.db(dbName)
      const collection = db.collection('reviews')
      const result = collection.find({}).limit(20)
      console.log(result)
      res.status(200).json({ result })

Instead of feedback, I get this
{
    "result": {
        "_events": {},
        "_eventsCount": 0
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Slava Rozhnev, 2021-07-29
@axrising

Accessing the database is asynchronous, so we use callback

const db = client.db(dbName)
const collection = db.collection('reviews')
collection.find().limit(20).toArray((err, result) => {
    if (err) throw err;
    console.log(result);
    db.close();
});

D
Dmitry Kuznetsov, 2021-07-29
@dima9595

It's likely that everything is working correctly for you. In the method collection.find({}), you are passing an empty object. And as I understand it, the method find()takes a certain id or some object for selection. Yes, and find and limit can be used together.
Unfortunately, I don't know what kind of library you have, so this is purely theory.

R
Rag'n' Code Man, 2021-07-30
@iDmitriyWinX

The database access is asynchronous, so we use async/await

const db = client.db(dbName)
const collection = db.collection('reviews')

const result = await collection.find({}).limit(20)
console.log(result)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question