roman95
roman95

Reputation: 73

Unable to add array data to MongoDB collection

I have 2 URLs, one points to a different connection string and the other to local MongoDB instance. While I establish the connection to MongoDB using MongoClient with url1 and fetch the required data from a DB/collection and lastly store it in an array. Now I want to insert this array to a localhost MongoDB collection and on doing so I get MongoError: Topology is closed, please connect error.

app.js

var url1="someurl but not localhost";
var url2="mongodb://localhost:27017/";
router.get('/route1', function(req, res)
{
    MongoClient.connect(url1,{ useUnifiedTopology: true }, function(err, db) {
        if (err) throw err;
        var dbo = db.db("customer");
        dbo.collection("customer_report").find({}).toArray(function(err, result) {
          if (err!=null){
            console.log("Connection Failed!!"+err)
          }
          var customerArray =[];
          for(i=0;i<result.length;i++){
            backupArray.push({
                a: result[i].a,
                b: result[i].b,
                c: result[i].c,
                d: result[i].d,
            });    
          }
        console.log(customerArray);
        res.json({content:customerArray});
        db.close();
        MongoClient.connect(url2,{ useUnifiedTopology: true }, function(err, db1) { 
            //Trying to establish another mongodb connection wuth new url
            if (err) throw err;
            var dbo = db.db("localdb");
            dbo.collection("localcollection").insertMany(customerArray, function(err, res) {
                if (err) throw err;
                console.log("Number of documents inserted: " + res.insertedCount);
                db1.close();
            });
        });
        });
    }); 
});

And if I don't close db.close(); then the array data gets appended to first MongoDB collection and not the local MongoDB. Looking for a solution to handle two MongoClient at the same time or a way to insert the customerArray to local MongoDB collection.

Is there a workaround where I can add the array elements to my local MongoDB collection?

Upvotes: 0

Views: 49

Answers (2)

Ben
Ben

Reputation: 1276

In your second mongo connect block I think you want

var dbo = db.db("localdb");

to be

var dbo = db1.db("localdb");

Upvotes: 0

Wesley Weaver
Wesley Weaver

Reputation: 29

Have you made sure those credentials work in console commands? And have you made sure the last connection through the console is closed before trying to use them in the script?

Upvotes: 0

Related Questions