Sort by reverse order mongoose

May 2024 ยท 2 minute read

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: http://mongoosejs.com/docs/api.html#types_array_MongooseArray.sort

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

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoa3BuYmmDeX2OrKarrF2Xxm6%2BxK%2Bcq6uVYryzsMSrZKannpy8sL%2FE