简单的Node.js MongoDB Express迭代/循环收集

时间:2018-09-05 15:20:18

标签: node.js mongodb express mongoose

我正在尝试显示一个集合-在mongo shell内它很简单。

DB =测试
收藏=库存

> use testing
switched to db testing
> db.inventory.find();   // very easy and straight fwd

我的问题是,我似乎无法弄清楚如何在迭代过程中获取数据的句柄。我收到以下错误:

  

无法读取未定义的属性'find'

const express = require('express');
const router = express.Router();
const mdb = require('mongoose');

const MongoClient = require('mongodb').MongoClient;
const mongoDB = "mongodb://localhost/testing";  

mdb.connect(mongoDB);
mdb.Promise = global.Promise;

let db = mdb.connection;

router.get('/', function(req, res) {
    db.inventory.find(query).stream()
    .on('data', function(doc){
      // handle doc
      console.log("raw => " + doc);
      console.log("JSON => " + JSON.stringify(doc));
    })
    .on('error', function(err){
      console.log("Error: " + err)
    })
    .on('end', function(){
      console.log("iteration complete")
    });

});

提前谢谢

1 个答案:

答案 0 :(得分:0)

好,这对我有用: 数据库名称:“测试” 集合:“库存”

const express = require('express');
const router = express.Router();

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost/testing";  

router.get('/', function(req, res) {

  MongoClient.connect(url, { useNewUrlParser: true },  function(err, db) {
    if (err) throw err;
    let dbo = db.db("testing");

    var stream = dbo.collection("inventory").find().stream()
    stream.on('error', function (err) {
      console.error(err)
    })
    stream.on('data', function (doc) {
      console.log(doc)
    })
    .on('end', function(){
      // final callback
      console.log("iteration complete")
    });
  });

    //post blank page
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end();
});