I'm trying to insert documents from this weather API into my MongoDB. I keep getting Cannot read property '_id' of undefined
with these error
undefined
/Users/Ekom/WebstormProjects/WebApps/node_modules/mongodb/lib/mongo_client.js:236
throw err
^
TypeError: Cannot read property '_id' of undefined
at Collection.insertMany (/Users/Ekom/WebstormProjects/WebApps/node_modules/mongodb/lib/collection.js:513:17)
at Collection.insert (/Users/Ekom/WebstormProjects/WebApps/node_modules/mongodb/lib/collection.js:825:15)
at /Users/Ekom/WebstormProjects/WebApps/app.js:26:24
at connectCallback (/Users/Ekom/WebstormProjects/WebApps/node_modules/mongodb/lib/mongo_client.js:314:5)
at /Users/Ekom/WebstormProjects/WebApps/node_modules/mongodb/lib/mongo_client.js:233:11
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
app.js
mongodb.MongoClient.connect('mongodb://localhost:27017/weatherdb', function(error, database) {
if(error != null) {
throw error;
}
collection = database.collection('data');
weather.find({search: 'Ottawa, ON', degreeType: 'C'}, function(err, documents) {
if(err) console.log(err);
// console.log(JSON.stringify(documents, null, 2));
});
console.log(documents);
collection.insert(documents, { w:1
},
function (error, result) {
if (error != null) {
console.log("ERROR: " + error);
}
});
});
Please can someone who knows what I am doing wrong kindly point me in the right direction?
var mongodb=require("mongodb");
var weather = require('weather-js');
mongodb.MongoClient.connect('mongodb://localhost/weatherdb', function(error, database) {
if(error != null) {
throw error;
};
weather.find({search: 'Ottawa, ON', degreeType: 'C'}, function(err, documents) {
if(err) console.log(err);
console.log(documents);
database.collection('data').insert(documents,function (error, result) {
if (error) {
console.log("ERROR: " + error);
}
});
});
});
Your console.log
line was outside the callback function therefore unaware of "documents" and your insert statement was a bit off too, the code above worked for me.
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.