簡體   English   中英

使用Node.js驅動程序打印和更新MongoDB中的所有文檔

[英]Printing and updating all the documents in MongoDB using Node.js driver

我正在編寫一個腳本,該腳本應該獲取集合中文檔的數量,然后全部打印它們,然后更新每個文檔,事實是我在運行它時遇到錯誤:MongoError:連接已被應用程序關閉。 這是我嘗試將db.close()放在沒有幫助的幾個地方的代碼。

var request = require('request');
var cheerio = require ('cheerio');
var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;

var dbName = "yahooStocks";
var port = "27017";
var requiredCollection = "stocks"
var host = "localhost";


MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){

        if(error) throw error;
        console.log ("Connected to: " + "mongodb://" + host + ":" + port + "/" + dbName);
    function update () {

        db.collection(requiredCollection).count({}, function (error, numOfDocs) {
            if(error) throw error;
            console.log("the number of docs is : " , numOfDocs);

            for (i=1; i<10; i++) {
                var findOneQuery = {'_id' : i};
                db.collection(requiredCollection).findOne(findOneQuery, function (error, doc) {
                    if(error) throw error;

                    console.log(doc._id + ". Doc - > " , doc);

                }); // end of findOne

                //db.close();
            }

             db.close();
        }); // end of count




    }
update();
// db.close();
 }); // end of connection to MongoClien

您需要確保以異步方式運行那些查詢。 最好的方法是使用異步庫。 (此示例使用貓鼬)

使用異步庫: https : //github.com/caolan/async

var queries = [];

for (i=1; i<10; i++) {
    queries.push(db.collection(requiredCollection).findOne({'_id' : i}));
}

async.each(queries, function(query, callback) {
    query.exec(function(err, doc) {
      if (err) callback(err);

      console.log(doc._id + ". Doc - > " , doc);

      // do things here

      callback();
    });
}, function(err) {
    // when everything is complete.
});

您已經有了計數 ,如何在findOne回調中簡單地倒數。 因此,您可以知道循環中的這些操作何時全部完成,並安全地調用db.close()

暫無
暫無

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

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