简体   繁体   中英

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

I'm writing a script that should get the number of the documents in the collection and then print them all, and then update each of them, the thing is that i'm getting an error while running it: MongoError: Connection Closed by application. Here is my code i've tried to put the db.close() in several places it doesn't helped.

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

You need to make sure to run those queries in asynchronous manner. Best way to do it is to use async library. (this example is using mongoose)

Using async library: 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.
});

You've got the count , how about simply countdown in your callback of findOne . Hence you could know when are those operations in the loops all completed, and safely call db.close() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM