【问题标题】:Sorting in Mongoose doesnt work correctlyMongoose 中的排序无法正常工作
【发布时间】:2014-10-26 13:35:21
【问题描述】:

排序不适用于猫鼬,但我不明白这怎么可能,因为我已经搜索了这么多!任何时候我尝试它都不起作用。这是我的代码

Pics.find({}).limit(8).populate('creator').sort("created_at", 1).execFind(function(err, docs){
    console.log(docs);
});

我明白了:

TypeError: Invalid sort() argument. Must be a string or object.
at Query.sort (/Users/n/Proj/feetshot/node_modules/mongoose/lib/query.js:755:11)
at /Users/n/Proj/feetshot/app.js:112:45
at callbacks (/Users/n/Proj/feetshot/node_modules/express/lib/router/index.js:272:11)
at param (/Users/n/Proj/feetshot/node_modules/express/lib/router/index.js:246:11)
at pass (/Users/n/Proj/feetshot/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/Users/n/Proj/feetshot/node_modules/express/lib/router/index.js:280:4)
at Object.handle (/Users/n/Proj/feetshot/node_modules/express/lib/router/index.js:45:10)
at Context.next (/Users/n/Proj/feetshot/node_modules/express/node_modules/connect/lib/http.js:204:15)
at Context.<anonymous> (/Users/n/Proj/feetshot/node_modules/passport/lib/passport/context/http/actions.js:64:8)
at SessionStrategy.pass (native)

我怎样才能使排序工作?

这是我的架构:

var PicSchema = new Schema({
creator: { type: Schema.ObjectId, ref: 'Users' }
, body: String
, created_at: { type: Date, default: Date.now }
, link: { type: String, index: { unique: true } }
, twitter_id: { type: String, index: { unique: true } }
, tags: [String]
  , likes: [{ type: Schema.ObjectId, ref: 'Users' }]
   });

【问题讨论】:

  • 基本结构看起来还可以;你的 Pics 架构是什么样的?

标签: node.js mongodb mongoose


【解决方案1】:

根据您的错误消息,您必须使用 Mongoose 3.x,但是您使用的是 2.x sort 方法参数样式。切换到 2.7.0 Mongoose 版本或将排序用法更改为 sort('created_at')。来自 3.x 来源:

/**
* sort
*
* Sets the sort order. Accepts a single parameter, either an object or string.
* If an object is passed values allowed are 'asc', 'desc', 'ascending', 'descending', 1, -1.
* If a string is passed it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
*
* Examples:
*
* // these are equivalent
* query.sort({ field: 'asc', test: -1 });
* query.sort('field -test');
*
* @param {Object|String}
* @api public
*/

【讨论】:

  • 我使用猫鼬 3。我的问题是如何使用 desc ?
  • 知道了,但是如果我使用减号或不使用它,我仍然会得到相同的结果:S
  • 3.0 还没有发布,所以除非你特别需要 3.x 分支中的某些东西,否则我会坚持使用 2.7。
【解决方案2】:

尝试

  1. 使用字符串更正排序方法调用
  2. 在填充之前进行排序。

所以:

Pics.find({}).sort("created_at").limit(8).populate('creator').execFind(function(err, docs){
    console.log(docs);
});

【讨论】:

    猜你喜欢
    • 2018-04-26
    • 2021-06-15
    • 1970-01-01
    • 2020-12-14
    • 2012-03-29
    • 2018-07-18
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多