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
Model.findOne
has no method sort
. But you can use Model.find
, sort by your date (ascending or descending) and then limit the returned values to 1 with the limit
method :
col.find(q).sort(versionTimestamp: -1).limit(1).exec();
Here, sort
is a method and not a parameter of the method find
like q
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.