Nodejs querying single data instead of all from mongodb collection

Santosh

New Member
#1
I am trying to fetch data from mongodb's collection. My code is executing only single row data in json format. But when I console log my data I can see all the row data.
Mã:
const mongoose = require('mongoose');
const AllMinisters  = require('../models/allMinisters');
var db;
var mongodb = require("mongodb");

// Initialize connection once
mongoose.connect("******", { useNewUrlParser: true }, function(err, database) {
if(err) return console.error(err);
db = database;
// the Mongo driver recommends starting the server here because most apps *should* fail to start if they have no DB.  If yours is the exception, move the server startup elsewhere.
});

exports.getAllMinisters = (req,res,next)=>{
    db.collection("users").find({}, function(err, docs) {
        if(err) return next(err);
        docs.each(function(err, doc) {

        if(doc) {
            console.log(doc);
            var response = {
                statusCode: 200,
                headers:  { 'Content-Type': 'application/json' },
                body: doc
                }
                res.end(JSON.stringify(response));
        }
        });
    });
};
This output in JSON as

v4C7z.png

However the console report shows all

qVkkg.png

How can I show all row data in JSON
 

Admin

Administrator
Thành viên BQT
#2
You have docs.each in your code that will iterate over all the doc you get from the find() query (which is an array) and inside that each block you are sending the response i.e, res.end(JSON.stringify(response));, which executes immediately for the first record and hence you get a single object as a response instead of array.

To return the array you need to put res.end(JSON.stringify(response)); outside the each() loop with toArray function. You can even remove the each() loop if that is not required. So, your code will be something like:
Mã:
exports.getAllMinisters = (req, res, next)=>{
  db.collection('users').find({}).toArray(function (err, docs) {
    if (err) {return next(err);}
    docs.each(function (err, doc) {
      if (doc) {
        //code for single doc
        console.log(doc);
      }
    });
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(docs));
  });
};
 
OP
OP
S

Santosh

New Member
#3
I tried using res.next which seems not working. Can you help me fixing it please
 
OP
OP
S

Santosh

New Member
#5
That body:doc is empty right ? its not working still even after changing it to docs
 

Admin

Administrator
Thành viên BQT
#8
Then you need to use .exec on the find() query
check the updated answer
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top