【问题标题】:Node.js - Display mongoDB documents with console.log (No Shell)Node.js - 使用 console.log 显示 mongoDB 文档(无 Shell)
【发布时间】:2016-07-06 14:23:38
【问题描述】:

我正在使用位于另一台机器上的 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 将所有文档显示到控制台。

【问题讨论】:

  • Use print 而不是 console.log
  • @LuísSoares 现在它说print 未定义
  • 算了。你在 NodeJS .. 如果 MongoDB 控制台的答案:\

标签: javascript node.js mongodb


【解决方案1】:

你试过了吗?

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

【讨论】:

    【解决方案2】:

    好吧,如果您想查看每个单独的文档,请尝试以下功能 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 });
      });
    

    【讨论】:

      猜你喜欢
      • 2013-07-25
      • 2023-03-19
      • 1970-01-01
      • 2020-03-12
      • 1970-01-01
      • 2014-10-31
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多