0

I am not able to understand why the inserted MongoDB document although it contains items, the code is not able to iterate over. The cursor object itself is not null. I am able to retrieve the documents using db.newmongo.find()

var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
db.collection("newmongo").insert([{"name": "XXX", "age": "50"},
                     {"name": "YYY", "age": 43},
                     {"name": "ZZZ", "age": 27},
                     {"name": "AAA", "age": 29},
                     {"name": "BBB", "age": 34}]); 

console.log("Connected correctly to server.");  
var cursor=db.collection('newmongo').find();
console.log(cursor);  // This gets logged
cursor.each(function(err, doc) {      
      if (doc != null) {
         console.log('Document found');
      } else {
         console.log('Document not found');
      }
});
Vibes
  • 33
  • 6
  • 1
    Why is it a duplicate? Because yet another person using an async call like `.insert()` is but then trying to look for that result immediately afterwards, **without** "Putting the code that follows that operation **inside** the callback for that operation". You're using synchronous coding techniques with async functions. Understand these calls do not block until completion before the following lines of code are run. Callbacks. – Blakes Seven Feb 28 '16 at 06:17
  • It seems like there is an error in the JSON document that you are trying to insert – Nidhin David Feb 28 '16 at 06:41

1 Answers1

1

You should always check if the records were inserted correctly without any errors. To do that you must pass a callback to the insert method. Something like this :

var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
if(err){
  console.log("Error connecting to MongoDB");
  return;
}
console.log("Connected correctly to server.");  
db.collection("newmongo").insert([{name: "XXX", age: 50},
                 {name: "YYY", age: 43},
                 {name: "ZZZ", age: 27},
                 {name: "AAA", age: 29},
                 {name: "BBB", age: 34}], function(err, docs){
    if(err){
        console.log("Error inserting documents in MongoDB : " + JSON.stringify(err));
    }
    if(docs){
        console.log("Following Documents were Successfully Inserted : \n" + JSON.stringify(docs));
    }
});

Also since this is an async call, it will not wait till the inserting of documents is done and will fire the find instantly. Due to this, you might not be able to get any records in the newmongo collection as the write operation is still in progress.

So what I suggest is to call find only after the if(docs) condition.

And I also think that calling find is not necessary as the docs parameter that was returned in the callback would return the docs successfully written in your collection. So you can directly log them to console as shown in the above example.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110