0

I am having a hard time trying to find the last inserted element into mongo. I am using an example code I found and trying to make the query and display the item but I am getting an error. I understand I am suppose to do something like this.

db.collectionName.findOne({}, {sort:{$natural:-1}})

But this is what I have so far and it's not working.

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(err) { return console.dir(err); }

  var collection = db.collection('test');
  var doc1 = {'hello':'doc1'};
  var doc2 = {'hello':'doc2'};
  var lotsOfDocs = [{'hello':'doc3'}, {'hello':'doc4'}];

  collection.insert(doc1);
  collection.insert(doc2, {w:1}, function(err, result) {});
  collection.insert(lotsOfDocs, {w:1}, function(err, result) {});

  collection.find({}).toArray(function(err, docs) {
    console.log(docs[0]);
  });

  db.close();
});

This is the error.

nodejs/node_modules/mongodb/lib/mongodb/connection/base.js:246
        throw message;
              ^
TypeError: Cannot read property '0' of null

I checked to make sure the database is not empty so I am not sure why it's returning null.

Kelvin
  • 2,218
  • 4
  • 22
  • 41
  • What is wrong with using the [**reverse order**](http://docs.mongodb.org/manual/reference/operator/meta/natural/#reverse-order) of the `$natural` operator: `collection.find({}).sort( { $natural: -1 } )toArray(..)` or simply `collection.find().sort({ $natural: -1 }).limit(1)` to get the last document inserted? – chridam Mar 13 '15 at 09:43
  • i can't really test that because i can't get `collection.find({}).toArray(function(err, docs) { console.log(docs[0]); });` to work at the moment – Kelvin Mar 13 '15 at 09:45
  • any idea what is wrong with that? i am having problems with querying anything trying to console.log it at the moment – Kelvin Mar 13 '15 at 09:47
  • @ShinonChan Have you tried checking if the docs object is null before accessing its first element? What will show up in the console if you log the docs object? – vladzam Mar 13 '15 at 10:07
  • Did you try logging `err` to see if you get an error message? – Philipp Mar 13 '15 at 10:11
  • @Philipp I get `{ [MongoError: Connection Closed By Application] name: 'MongoError' }` if i log the err – Kelvin Mar 13 '15 at 10:17
  • @VladZ. i get the `null` when i log the docs object – Kelvin Mar 13 '15 at 10:20
  • Do you have created timestamp field ? – Anubhav Singh Mar 13 '15 at 10:43

1 Answers1

3

I've found a possible solution(here) to your problem. It might be due to the fact that the database connection closes before the operations that you have issued finish.

You can fix it by including the db.close() call inside the find query.

 collection.find({}).toArray(function(err, docs) {
    console.log(docs[0]);
    db.close();
  });
Community
  • 1
  • 1
vladzam
  • 5,462
  • 6
  • 30
  • 36