Wednesday, 19 April 2017

Unable to insert data to mongoDB through my nodejs code

I have my mongo DB set up and running in the google cloud server. I have my nodejs code in the server which tries to connect to the database and insert data into a collection. But this doesn’t seem to be working. The data does not get inserted. It does not throw any specific error message. When I manually create a database in mongoShell and insert data into a collection, the data gets inserted. I also have my code connecting to mongo DB locally in my system and inserting data which still works fine.

What do you think could be a problem here? Below is the code snippet for connecting to mongo DB and inserting data.

function insertDataInMongo(a) {

    var deferred = q.defer();

    var MongoClient = require('mongodb').MongoClient;
    var url = 'mongodb://localhost/MyMongoDB’;
    var token = a[1];
    MongoClient.connect(url,function (err,db) {
        if(err) deferred.reject(new Error(err))
        console.log("connected for insert");


        var apiData = JSON.parse(a[0]);

        if(apiData.data){


            db.collection(‘TestCollection1’).update(apiData.data, {upsert:true});
            console.log(“Data inserted in TestCollection1“);
        }

        else {

            db.collection(‘TestCollection2’).update(apiData, {upsert:true});
            console.log(“TestCollection2”);
        }

        deferred.resolve(token);

    });

    return deferred.promise;
}



via SAS

No comments:

Post a Comment