0

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?

WCPOH
  • 1
  • 1
  • 4
  • Sorry. Can you explain how the question is the same? The error may appear to be the same. But the possible causes may be different, right? Thanks. – WCPOH Jun 21 '17 at 09:40

1 Answers1

0

The insert() returns a WriteResult object that contains the status of the operation. Upon success, the WriteResult object contains information on the number of documents inserted:

WriteResult({ "nInserted" : 1 })
mn.agg
  • 281
  • 1
  • 8