Sorting mongodb client findOne() in node

拟墨画扇 提交于 2019-12-23 22:12:07

问题


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.");
                    }
                }
            });

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/44531148/sorting-mongodb-client-findone-in-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!