无法阅读财产' _id'未定义的

时间:2017-01-29 22:37:56

标签: javascript mongodb weather-api

我试图将此weather API中的文档插入到我的MongoDB中。我不断收到Cannot read property '_id' of undefined这些错误

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);
                    }
                });



});

请知道我做错事的人能否指出我正确的方向?

1 个答案:

答案 0 :(得分:0)

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);
            }
        });
    });
});

您的console.log行不在回调函数之内,因此不知道"文档"而且你的插入语句也有点过了,上面的代码对我有用。