Somehow this code from Chapter 7 of "Web Development with MongoDB and Node.js" doesn't work.
Can anyone explain why and also suggest possible fix?
It seems the issue is with doc[0]._id
If I comment out line [10], I won't see the error.
Here is the full code copied directly from the book.
1 var MongoClient = require('mongodb').MongoClient;
2
3 MongoClient.connect('mongodb://localhost:27017/mongotest', function(err, db) {
4 console.log('Connected to MongoDB!');
5
6 var collection = db.collection('testing');
7 collection.insert({'title': 'Snowcrash'}, function(err, docs) {
8 console.log(docs.length + ' record inserted.');
9 console.log(docs[0]._id + ' - ' + docs[0].title);
10
11 collection.findOne({title: 'Snowcrash'}, function(err, doc) {
12 console.log(doc._id + ' - ' + doc.title);
13 db.close();
14 });
15 });
16 });
After some googling, I found the the fix.
MongoDB. Undefined record inserted. Cannot read property 'title' of undefined
console.log(docs.ops.length + ' record inserted.');
console.log(docs.ops[0].title + ' – ' + docs.ops[0]._id);
Found more clues: Check out https://www.w3schools.com/nodejs/nodejs_mongodb_insert.asp See the paragraph on Result Object.
Still, can anyone explain how adding .ops made the difference?
Also, for line [9], why is there a need to add [0] after docs?