louischatriot / nedb

The JavaScript Database, for Node.js, nw.js, electron and the browser
MIT License
13.49k stars 1.03k forks source link

Retrieving most recent document returns incorrect documents #522

Open TheMaverickProgrammer opened 7 years ago

TheMaverickProgrammer commented 7 years ago

`var cursor = db.find({name: 'session'}).sort({timestamp:-1}).limit(1);

cursor.exec( function(err, docs) { if(!err && !(docs == null) && docs.length > 0) { console.log("docs.length: " + docs.length); docs.forEach(function(d) { console.log("d._id: " + d._id + " d.array: " + JSON.stringify(d.array)); event.sender.send('labelContents', d.array); }); } else { event.sender.send('labelContents', null); console.log("error: " + err); } } );`

Problem is simple to understand: I insert new documents and expect to return the most recently added document from the datastore. Instead I receive a document from a later time. Here is my output. Notice the IDs do not match from most recent insert:

`Inserted session with ID fvNHKyS6G0j5x1xN

Inserted session with ID cla0VItr8nDxbvON returning latest: d._id: 2hwVJ14rkT98gLIA d.array: [] Inserted session with ID kDLOapyhuJWTcdhK returning latest: d._id: 2hwVJ14rkT98gLIA d.array: [] Inserted session with ID eprACGQFAzzYEJ2p Inserted session with ID Zxv3NaiUZ2EqyCe1 Inserted session with ID IDljMKPhLg83fbJO Inserted session with ID 07a68T6YVwIPkOFD returning latest d._id: Zxv3NaiUZ2EqyCe1 d.array: [...redacted...]`

Using Nedb 1.8.0

TheMaverickProgrammer commented 7 years ago

I have also tried using {$natural: -1} and {x: -1} both with similar results

TheMaverickProgrammer commented 7 years ago

I've found a work around by adding a timestamp property to each document I insert and sorting by that. This does not mean that the sort issue is resolved in the library.

JamesMGreene commented 7 years ago

@TheMaverickProgrammer: How would you ever expect this to work without the timestamp property being present on documents?

TheMaverickProgrammer commented 7 years ago

@JamesMGreene MongoDB includes timestamps. This library claimed to be analogous to MongoDB.

JamesMGreene commented 7 years ago

@TheMaverickProgrammer: I've never encountered automatically included timestamp fields in MongoDB, other than if you sort by documents' ObjectIds. If I'm mistaken, please link me to some documentation as I'd be interested to learn more.

As for NeDB, the analog would be:

var db = new Datastore({ inMemoryOnly: true, timestampData: true });
db
  .find({ name: 'session' })
  .sort({ createdAt: -1 })      // OR `.sort({ updatedAt: -1 })` to sort by last modification time
  .limit(1)
  .exec(function(err, docs) {
    /* ... */
  });