简体   繁体   中英

Insert Multiple Data in MongoDB

I'm using this weather API to collect data and store in MongoDB. However, I would like to store data for multiple locations. So far, I can do it just one. So far my data shows as null in my MongoDB.

mongodb.MongoClient.connect('mongodb://localhost/weatherdb', function(error, database) {
    if(error != null) {
        throw error;
    };

  var t =  weather.find({search: 'Montreal, Canada', degreeType: 'F'}, function(err, result1) {
        if(err) console.log(err);


    });

  var x =  weather.find({search: 'Ottawa, Canada', degreeType: 'F'}, function(err, result2) {
        if(err) console.log(err);


    });

 var y =   weather.find({search: 'Toronto, Canada', degreeType: 'F'}, function(err, result3) {
        if(err) console.log(err);


    });
    database.collection('data').insert(
        {
            Montreal: t,
            Ottawa : x,
            Toronto : y
        },function (error, result) {
        if (error) {
            console.log("ERROR: " + error);
        }
    });

});

I will be grateful if someone could show me how to do this.

The issue is that each of your queries is asynchronous, but you're not capturing their results into the variables like you think you are. The results of each of those find operations is only available inside its callback function. However, however you can do better flow control than nesting all the callbacks. Flow control can be done with Promises or the Asyncjs library, I vastly prefer the latter.

With async.map you can iterate over the queries you're trying to make, something like this

var queries = { 't' : {search: 'Montreal, Canada', degreeType: 'F'}, 'x': {search: 'Ottowa, Canada', degreeType: 'F'}, 'y': {search: 'Toronto, Canada', degreeType: 'F'}]

async.mapValues(queries, function(query, key, cb) { weather.find(query, cb); }, function(err, results) {
  database.collection('data').insert(
        {
            Montreal: results.t,
            Ottawa : results.x,
            Toronto : result.y
        },function (error, dbResult) {
        if (error) {
            console.log("ERROR: " + error);
        }
    });
});

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