Pegasus18
Pegasus18

Reputation: 300

How to order responses in Mongoose?

When retrieving data from my database the Schema's order is not maintained and the response is not in the format I need. I need the response to be the same as the Schema, the response I get is in this order:

Response

[
 {
  "comments": [],
  "_id": "5ede3608c9cd033744641188",
  "title": "Book 1",
  "__v": 0
 },
 {
  "comments": [],
  "_id": "5ede360cc9cd033744641189",
  "title": "Book 2",
  "__v": 0
 }
]

Book Schema:

const bookSchema = new mongoose.Schema({
    title: String,
    commentCount: Number,
    comments: [String]
  }, {collection: 'fcclibrary'});

  const Book = mongoose.model('Book', bookSchema);

POST request

.post(function (req, res){
      let title = req.body.title;
      let newBook = new Book({
        title: title
      });
      newBook.save((err, book) => {
        if(err) {
          console.log(err);
        } else {
          console.log(book);
          res.json({title: book.title, id: book.id});
        }
      })
    })

GET request

app.route('/api/books')
    .get(function (req, res){
      Book.find({}, (err, found) => {
        if(err) {
          console.log(err);
        } else {
          console.log(found);
          res.json(found);
        }
      })

How can I preserve order of my Schema when retrieving it from the DB? I have already tried retainKeyOrder: true.

Upvotes: 1

Views: 742

Answers (1)

Mercury
Mercury

Reputation: 7988

First make sure you are using Mongoose 4.6.4 or above (Mongoose docs) It's odd that the retainKeyOrder did not work for you (never tried it myself but please double check)

In addition here are a few StackOverflow posts that discusses about a very similar case as yours:

Sort Keys in Response Object from Mongoose in ExpressJS and NodeJS

Using a "replacer" to create the output order that you want

Upvotes: 1

Related Questions