Sort by Reverse Order Mongoose

Sort by Reverse Order Mongoose

Hi, I am trying to return my query in backwards order from which it was created.
The docs are a little unclear on how to use the sort method:

Here is my schema:

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);

I have run,

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

For example, if my model was a 'Post' model and my first post was 'hello world' and my second post was 'this is a post'. I would like to see:

 ['this is a post', 'hello world']

However, what I am actually seeing is ['hello world','this is a post']

1

2 Answers

Figured out the answer

in posts schema add:

date: {
    type: Date,
    default: Date.now
}

then db.posts.find().sort({date:-1}).pretty() will yield the posts sorted from most recent to least recent

You have to add a creation timestamp in your schema and sort by its key.

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
    }
})

and when you insert a document, use:

date: new Date()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.