javascript - 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));
}
});
});
};
However the console report shows all
How can I show all row data in JSON
解决方案
您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));
});
};
推荐阅读
- android - 如何从 RGB 中的 android 相机获取图像?
- php - 在 wordpress 中使用 AMP 插件时,表单发布方法不起作用
- scala - 如何使用 scala-cache API 将对象集合存储到内存缓存中
- c# - 通过套接字c#发送base64字符串
- .net - 如何在 LINQ 查询提供程序 (ExpressionVisitor) 中调用函数或属性
- sql - 如何在spring数据存储库本机查询中向IN子句添加参数
- python - 尝试在 python 命令中查看已安装模块的列表会弹出一个空白的 kivy 应用程序窗口
- asp.net - 我想在我的 SQL 连接字符串中加入 Enlist=False 吗?
- python - 如何检索 Apache Kudu 表列的 MIN 值?
- python - 错误:安装 psutil 时命令“gcc”以退出状态失败