按逆序排序猫鼬

mda*_*sh1 6 mongoose mongodb node.js

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

这是我的架构:

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);
Run Code Online (Sandbox Code Playgroud)

我跑了,

db.posts.find().sort({date:-1}).pretty()
Run Code Online (Sandbox Code Playgroud)

例如,如果我的模型是“Post”模型,我的第一篇文章是“hello world”,而我的第二篇文章是“this is a post”。我想看看:

 ['this is a post', 'hello world']
Run Code Online (Sandbox Code Playgroud)

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

mda*_*sh1 5

想出了答案

在帖子架构中添加:

date: {
    type: Date,
    default: Date.now
}
Run Code Online (Sandbox Code Playgroud)

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


Rap*_*Mex 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
    }
})
Run Code Online (Sandbox Code Playgroud)

当您插入文档时,使用:

date: new Date()
Run Code Online (Sandbox Code Playgroud)