Get error node.js mongodb cannot read property 0 o

2019-05-31 17:49发布

问题:

I used db.collection.insert method to add a document in mongodb with function(err,records) callback. Though insertion succeeds (I checked on mongolab the record), records is null so that It throws error at records[0]._id

Is it a node.js bug on nitrous.io which I'm testing ?

MongoClient.connect(uri, function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");

        // Insert document in MongoDb Collection
                var document = {title:'test',category:'node.js'}

                db.collection('tut').insert(document, function(err,records){
                        //if (err) throw err;
                        console.log('inserted record id: ' + records[0]._id);
                  });
    }
    db.close();
});

回答1:

You're closing the connection before the insert call completes. Move your db.close(); call inside the callback:

MongoClient.connect(uri, function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");

        // Insert document in MongoDb Collection
        var document = {title:'test',category:'node.js'}

        db.collection('tut').insert(document, function(err,records){
            //if (err) throw err;
            console.log('inserted record id: ' + records[0]._id);
            db.close();
        });
    }
});

Keep in mind that you shouldn't be frequently opening and closing your MongoClient connection pool. It's generally best to open it during startup and leave it open until your app shuts down.