Deke
Deke

Reputation: 4649

not able to return the data in the `response.json `

I'm using mongoCleint to connect to the database using node server. Able to post the data to the database and able to read back the data in JSON.stringify(items) but not able to return it. Problem is that res.json(getRequest) in not giving back any json despite 'JSON.stringify(items)` is giving me a list of items. Am I not doing it right?

app.get('/getItems', function (req, res) {
    var getRequest;
    MongoClient.connect(url, function(err, client) {
       if(err){
         console.log("there is an error")
       } else {
         console.log("running get request")
         const db = client.db(dbName);
         db.collection('documents').find({}).toArray(function(err, items) {
           if(err) { 
             console.error(err) 
           } else {
             console.log(JSON.stringify(items))
             getRequest = JSON.stringify(items)
           }
         })
         client.close();
        }
     });
   console.log(res.json(getRequest))
   return res.json({ success: true, data: getRequest });
})

Upvotes: 0

Views: 68

Answers (2)

Cider
Cider

Reputation: 325

The callbacks run asynchronously but you don't wait for them. Consider running the following code:

app.get('/getItems', async function (req, res) {

    const client = await MongoClient.connect(url)

    const db = client.db(dbName)
    const getRequest = await db.collection('documents').find({}).toArray()

    client.close()
    return res.json({ success: true, data: getRequest })
})

Upvotes: 2

Nico
Nico

Reputation: 179

I tried to comment @Cider 's response but I don't have enough points.. I think it's ok but is lacking the res.json so It won't return anything.

I'd do it this way:

app.get('/getItems', async function (req, res) {

    const client = await MongoClient.connect(url)

    const db = client.db(dbName)
    const getRequest = await db.collection('documents').find({}).toArray()

    client.close()
    return res.json({ success: true, data: getRequest })
})

Upvotes: 0

Related Questions