簡體   English   中英

Node.js - 使用 console.log 顯示 mongoDB 文檔(無外殼)

[英]Node.js - Display mongoDB documents with console.log (No Shell)

我正在使用位於另一台機器上的 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 將所有文檔顯示到控制台。

你試過這個嗎?

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

好吧,如果您想查看每個單獨的文檔,請嘗試使用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 });
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM