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
.