我正在尝试从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中的所有行数据
答案 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));
});
};