猫鼬默认排序顺序

猫鼬默认排序顺序

本文介绍了猫鼬默认排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在Mongoose中指定模式/模型级别的排序顺序?

Is there a way to specify sorting order on the schema/model level in Mongoose?

我有模型Posts,并且我总是提取'createdAt'字段排序的帖子.因此,在每个查询上我都必须写.sort('-createdAt').我可以将此型号的订单默认设置吗?

I have model Posts, and I always fetch posts ordered by 'createdAt' field. Thus on each query I have to write .sort('-createdAt'). Can I make this order default for this model?

推荐答案

在Mongoose中,无法直接定义查询的默认排序顺序.

There is no way, in Mongoose, directly to define a default sort order on your query.

但是,如果您要一遍又一遍地做某事,则可能希望将其抽象为一个为您完成的功能:

If you're doing something over and over again though, you might want to abstract this into a function that does it for you:

function findPostsByDate(cb){
    Posts.find({}).sort('-createdAt').exec(cb);
}

或更通用的东西:

function findXByDate(model, findCriteria, cb){
    model.find(findCriteria).sort('-createdAt').exec(cb);
}

这篇关于猫鼬默认排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:42