Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: 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']

like image 226
mdash1 Avatar asked Dec 03 '17 23:12

mdash1


People also ask

How do I reverse the order of data in MongoDB?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

What is sort in Mongoose?

sort() takes an object as parameter where the values are 1 or -1. Use -1 for descending order and 1 for ascending.

What is __ V 0 in Mongoose?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).


1 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

like image 156
mdash1 Avatar answered Oct 05 '22 23:10

mdash1