Node.js - 使用console.log显示mongoDB文档(无Shell)

时间:2016-07-06 14:23:38

标签: javascript node.js mongodb

我正在使用位于另一台计算机上的mongoDB服务器。我的问题是如何显示使用console.log找到的所有文档?目前我的main.js脚本是这样的:

// Connect to Mongo
MongoClient.connect('mongodb://10.254.17.115:27017/ExpressOrder', function(err, db) {

// Handle errors
assert.equal(null, err);
    // Insert data
    db.collection('ExpressOrder').insert({"SID":"24676637"});
    // Count data
    db.collection('ExpressOrder').find().count().then(function(numItems) {
        console.log(numItems); // Use this to debug
        callback(numItems);
    })
    // Display all data in db
    var found = db.collection('ExpressOrder').find();
    console.log(found); // Use this to debug
});

数据已正确插入并正常计数,但我现在需要知道如何使用console.log将所有文档显示到控制台。

2 个答案:

答案 0 :(得分:1)

你试过这个吗?

var found = db.collection('ExpressOrder').find();
found.each(function(err, doc) {
    assert.equal(err, null);
    if (doc != null) {
        console.log(doc);
    }
});

答案 1 :(得分:0)

好吧,如果您想查看每个个人文档,请尝试使用功能 each()下面的代码

 var db = mongoUtil.getDb();
  db.collection( 'products' ).find(function(err, docs){
    if (err) throw err;
    docs.each(function(err, doc){
      if(err) return console.err(err);
            // Log document
            console.log(doc)
    });
    res.render('shop/index', { title: 'Express', products:result });
  });
相关问题