首页 > 解决方案 > Nodejs querying single data instead of all from mongodb collection

问题描述

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.

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 enter image description here

However the console report shows all enter image description here

How can I show all row data in JSON

标签: javascriptnode.jsmongodb

解决方案


docs.each的代码将遍历docfind()查询中获得的所有内容(这是一个数组),并且在该each块内您正在发送响应,即res.end(JSON.stringify(response));,它会立即为第一条记录执行,因此您会得到一个对象作为响应而不是数组。

要返回数组,您需要将函数放在循环res.end(JSON.stringify(response));之外。如果不需要,您甚至可以删除循环。因此,您的代码将类似于:each()toArrayeach()

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));
  });
};

推荐阅读