Node.js 向mongoose find查询添加排序
首先,我做了一些备忘录的列表页 我想按创建备忘录的时间顺序加载备忘录 这意味着就像简单的SNS一样,我想让它们按堆栈顺序加载 这是添加了“created_at”的数据库架构Node.js 向mongoose find查询添加排序,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,首先,我做了一些备忘录的列表页 我想按创建备忘录的时间顺序加载备忘录 这意味着就像简单的SNS一样,我想让它们按堆栈顺序加载 这是添加了“created_at”的数据库架构 var StatSchema = mongoose.Schema({ id: {type: Number, unique: true, 'default':''}, ... created_at: {type: Date, index: {unique: false}, 'de
var StatSchema = mongoose.Schema({
id: {type: Number, unique: true, 'default':''},
...
created_at: {type: Date, index: {unique: false}, 'default': Date.now}
});
我有一个简单的方法来列出所有的备忘录。实际上,这是关于MongoDB线的
StatSchema.static('findAll', function(callback) {
return this.find({}, callback);
});
然后,我想添加属性“sort”,如
this.sort({'created_at':-1})
如何修改原始代码 在调用
find
时省略callback参数,将sort
调用链接到返回的Query
,然后调用exec
执行查询:
StatSchema.static('findAll', function(callback) {
return this.find({}).sort({'created_at':-1}).exec(callback);
});
非常感谢你!