Node.js查询单个数据而不是MongoDB集合中的所有数据

时间:2018-09-03 08:05:50

标签: javascript node.js mongodb

我正在尝试从mongodb的集合中获取数据。我的代码仅执行json格式的单行数据。但是,当我用控制台记录我的数据时,我可以看到所有行数据。

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

此输出在JSON中为 enter image description here

但是控制台报告显示所有 enter image description here

如何显示JSON中的所有行数据

1 个答案:

答案 0 :(得分:1)

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

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

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