Question

I am using mongojs to update data in a mongodb collection. The program reads a file line by line and for each line it makes an update in the mongodb database. The update is working fine but the control does not return.

var fs = require('fs')
var reader = require('buffered-reader');
var dataReader = reader.DataReader;

var mongojs = require('mongojs')
var db = mongojs.connect('testdb');
var col = db.collection('testCollection');

var file = "sample.txt";

var loadData = function (line) {
    record = line.split(",");
    rec_key = record[1];
    col.update(
        {rec_key: rec_key},
        {rec_key: rec_key,
         data: 5678},
        {upsert:true}, function(err){});
}

new dataReader (file, { encoding: "utf8" })
    .on ("error", function(error){
            console.log ("error: " + error);
        })
    .on ("line", loadData )
    .on ("end", function (end){
            console.log("EOF");
        }).read();

After running through this from node, the control does not return. The program is running indefinitely. If I comment the loadData function in dataReader it works fine, the program ends after iterating through all the lines.

How do I make the program to come to an end after iterating through all the lines and making an update in mongodb?

Était-ce utile?

La solution

You need to close your MongoDB connection when you're done with it or it will hold the program open.

Something like:

.on ("end", function (end){
        console.log("EOF");
        db.close();
    }

Autres conseils

   col.update(
    {rec_key: rec_key},
    {rec_key: rec_key,
     data: 5678},
    {upsert:true}, function(err){
        if(err)
          //return false
        else
          //return true
    });

I would suggest that you try using the node.js native driver instead as you can use the latest version.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top