社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  MongoDB

nodejs查询单个数据而不是来自mongodb集合的所有数据

Santosh • 5 年前 • 1653 次点击  

我正在尝试从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中显示所有行数据

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38683
 
1653 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Ankit Agarwal
Reply   •   1 楼
Ankit Agarwal    6 年前

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

要返回需要放置的数组 res.end(json.stringify(response)); 在外面 each() 循环 toArray 功能。你甚至可以移除 () 如果不需要,则循环。因此,您的代码将类似于:

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