按逆序mongoose排序

时间:2017-12-03 23:59:44

标签: node.js mongodb mongoose

嗨,我正在尝试以创建它的向后顺序返回我的查询。
有关如何使用sort方法的文档有点不清楚: http://mongoosejs.com/docs/api.html#types_array_MongooseArray.sort

这是我的架构:

"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\Roslyn\csc.exe" MyApplication.cs

我跑了,

const mongoose = require('mongoose'), 
    Schema     = mongoose.Schema,
    ObjectId   = Schema.Types.ObjectId;

let PostSchema = new Schema({
    title      : String,
    description: String,
    image      : String,
    tags       : [String],
    original_poster: {  
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    date: {
       type: Date,
       default: new Date()
   }
})



module.exports = mongoose.model('Post',PostSchema);

例如,如果我的模型是'Post'模型,我的第一个帖子是'hello world',而我的第二个帖子是'这是一个帖子'。我想看看:

db.posts.find().sort({date:-1}).pretty()

然而,我实际看到的是 ['this is a post', 'hello world']

2 个答案:

答案 0 :(得分:1)

找出答案

帖子架构中的

添加:

[2, 3, 5, 7, 11, 13, 17, 19, 23]

然后db.posts.find()。sort({date:-1})。pretty()将产生从最近到最近排序的帖子

答案 1 :(得分:0)

您必须在架构中添加创建时间戳并按其键排序。

let PostSchema = new Schema({
    title      : String,
    description: String,
    date       : Date, // Here is your date
    image      : String,
    tags       : [String],
    original_poster: {  
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    }
})

当您插入文档时,请使用:

date: new Date()
相关问题