I wrote a Mongoose Node/Express application. I have 4 documents. I am trying to write a route (end point) to get all seats for a table with their full data. I get a response like I expect.
I want to know if there is a better way to write the application like this.
seat.model.js
const mongoose = require('mongoose');
const SeatScheme = mongoose.Schema({
table: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Table',
required: true
},
event: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Event',
require: true
}
});
module.exports = mongoose.model('Seat', SeatScheme);
course.model.js
const mongoose = require('mongoose');
const CourseSchema = mongoose.Schema({
seat: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Seat'
},
meal: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Meal'
}
});
module.exports = mongoose.model('Course', CourseSchema);
meal.model.js
const mongoose = require('mongoose');
const MealSchema = mongoose.Schema({
name: String,
img: String,
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category'
}
});
module.exports = mongoose.model('Meal', MealSchema);
category.model.js
const mongoose = require('mongoose');
const CategorySchema = mongoose.Schema({
displayname: String,
type: String
});
module.exports = mongoose.model('Categoty', CategorySchema);
seat.route.js
const Seat = require('../../models/seat/seat.model');
const Course = require('../../models/course/course.model');
const Meal = require('../../models/meal/meal.model');
const Category = require('../../models/category/category.model');
module.exports = function (Router) {
Router.get('/seats/:tableid', (req, res) => {
Seat.find({ table: req.params.tableid }, (err, seats) => {
const seatsPromise = seats.map(seat => {
return Course.find({ seat: seat._id }).then((courses) => {
return Promise.all(courses.map(course => {
return Meal.findOne({ _id: course.meal }).then(meal => {
return Category.findOne({ _id: meal.category}).then(category => {
return {
displayname: category.displayname,
type: category.type,
meal: meal
}
})
})
})).then( courses => {
return {
seat: seat._id,
courses: courses
};
});
})
});
Promise.all(seatsPromise).then(seats => {
res.json(seats);
})
})
});
}