在节点中对mongodb客户端findOne()进行排序 [英] Sorting mongodb client findOne() in node

查看:1075
本文介绍了在节点中对mongodb客户端findOne()进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Lambda和Node.js在AWS中构建无服务器应用程序.我目前在mLab上有一个MongoDB.我试图获取基于ISODate字符串的最新"记录.使用findOne()或find w/limit 1每次都会返回相同的记录(而不是最新的记录).

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).

我的测试表中有2条记录,如下所示:

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" }

无论我做什么,它总是从6号返回一个.

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

或限制为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找到了!排序选项中的格式不正确的数组:

Asya found it! It was a malformed array in sort option:

sort接受一组排序首选项,默认为'asc'.我是 猜测您需要另一组数组括号:[['field','desc'] ] –昨天的Asya Kamsky

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

这篇关于在节点中对mongodb客户端findOne()进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆