I am building a server-less app in AWS with Lambda and Node.js. I currently have a MongoDB out at mLab. I am attempting to get the "latest" record based on an ISODate string. Using either findOne() or find w/limit 1 it returns the same record everytime (not the latest one).
I have 2 records in my test table that look like:
{ "field1": "myField", "versionTimestamp": "2017-06-13T18:33:06.223Z" }
{ "field1": "myField", "versionTimestamp": "2017-12-13T18:33:06.223Z" }
No matter what I do it always returns the one from the 6th
col.findOne(q, { "sort": ['versionTimestamp', 'desc'] }, function (err, doc) {
db.close();
if (err) {
sendErrorResponse("500", "Unable to query DB", err);
}
else {
if (doc) {
console.log(doc);
callback(null, doc.invoiceDocument);
}
else {
sendErrorResponse("404", "Record Not Found", "No records found that match those parameters.");
}
}
});
Or with limit 1
col.find(q, { "limit": 1, "sort": ['versionTimestamp', 'desc'] }).toArray(function (err, docs) {
db.close();
if (err) {
sendErrorResponse("500", "Unable to query DB", err);
}
else {
if (docs) {
console.log(docs[0]);
callback(null, docs[0].invoiceDocument);
}
else {
sendErrorResponse("404", "Record Not Found", "No records found that match those parameters.");
}
}
});
Asya found it! It was a malformed array in sort option:
sort takes an array of sort preferences, default being 'asc'. I'm guessing you want another set of array brackets: [ [ 'field', 'desc'] ] – Asya Kamsky yesterday
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With