【问题标题】:mongoose findOne with sorting带有排序功能的猫鼬 findOne
【发布时间】:2012-11-06 17:47:40
【问题描述】:

我对 mongo 请求有疑问:

models.user.findOne(
    {},
    {
        sort: {
            date_register: -1
        }
    },
    function(err, result) {
        console.log(err);
}

我有

{ [MongoError: Error: Unsupported projection option: date_register] name: 'MongoError' }

错误

我想通过 date_register DESC 获取我的用户

谢谢

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    这将根据您的 mongoose 版本略有不同,但 findOne 的方法签名看起来像这样:

    function findOne (conditions, fields, options, callback)
    

    您打算使用options(排序),猫鼬正在处理fields(要加载哪些字段)。

    您可以尝试为字段显式传递null

    models.user.findOne({}, null, { sort: { date_register: -1 } }, callback);
    

    但如果可以的话,你可能应该使用查询 API,它更清晰,例如:

    models.user.findOne({}).sort({ date_register: -1 }).exec(callback);
    

    【讨论】:

    • 第二个例子对我来说看起来很糟糕。.findOne({}).sort(..) 不会从 Mongoose 返回一条记录然后对结果进行排序? IE。排序将仅应用于返回的单个记录,假设 Mongoose 使用 Mongo 中的底层 .findOne() 函数,returns the first document according to the natural order which reflects the order of documents on the disk. docs.mongodb.org/manual/reference/method/db.collection.findOne
    • 不,因为猫鼬查询的工作方式。许多 mongoose 方法,如果未传递回调,将返回一个 Query 对象,该对象允许将发送给 mongoose 的查询分段构建。在示例中,findOnesort 被链接起来,最终在调用 exec 时构造成一个查询。
    • @numbers1311407,我们在 mongo shell 中有 findOne().sort() 吗?
    猜你喜欢
    • 2016-11-18
    • 2015-06-16
    • 2023-03-26
    • 2015-05-19
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2011-10-25
    相关资源
    最近更新 更多