[英]Nodejs querying single data instead of all from mongodb collection
我正在嘗試從 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 中顯示所有行數據
您的代碼中有docs.each
,它將遍歷您從find()
查詢(這是一個數組)中獲得的所有doc
,並且在您發送響應的each
塊中,即res.end(JSON.stringify(response));
,它會立即針對第一條記錄執行,因此您將獲得一個對象作為響應而不是數組。
要返回數組,您需要放置res.end(JSON.stringify(response));
在帶有toArray
函數的each()
循環之外。 如果不需要,您甚至可以刪除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));
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.