Reputation: 139
I am trying to determine a better way for my query. I have two tables, one is for recipes, and another is for reviews. Currently, I have two separate queries to find the recipe, and then find the reviews associated with the recipe. Is there a better way I could be doing this?
RecipeController
module.exports = {
viewRecipe: function(req, res) {
var recipeId = parseInt(req.params.id, 10);
var recipeM = {};
var reviewM = {};
db.recipe.find({
where: {
id: recipeId
}
}).then(function(recipe) {
recipeM = recipe.dataValues;
recipeM.ingredients = recipe.ingredients.replace(/\s+/g, '').split(",");
recipeM.instructions = recipe.instructions.split("\n");
}, function (e) {
});
db.review.findAll({
where: {
recipeId: recipeId
}
}).then(function(review) {
console.log(review);
res.render('viewRecipe', { recipe: recipeM, review: review, categories: categoriesMain, title: recipeM.title });
}, function(e) {
});
},
Upvotes: 0
Views: 497
Reputation: 412
If you have a relationship set up between a recipe and its reviews, I believe you can use Sequelize's include option as follows:
db.recipe
.findById(req.params.id, {
include: [{
model: review
}]
})
.then(function(recipe) {
// your success code
})
.catch(function(err) {
// you error code
});
As far as I know, the include option works as a left join. Also, this should perform better since only one query will be ran on the database.
Upvotes: 0
Reputation: 1662
If you are permitted to use ES6 generator, you can apply co.wrap from npm module co
module.exports = {
viewRecipe: co.wrap(function*(req, res) {
var recipeId = parseInt(req.params.id, 10);
var recipeM = {};
var reviewM = {};
var recipe = yield db.recipe.find({
where: {
id: recipeId
}
});
recipeM = recipe.dataValues;
recipeM.ingredients = recipe.ingredients.replace(/\s+/g, '').split(",");
recipeM.instructions = recipe.instructions.split("\n");
var review = yield db.review.findAll({
where: {
recipeId: recipeId
}
});
console.log(review);
res.render('viewRecipe', { recipe: recipeM, review: review, categories: categoriesMain, title: recipeM.title });
}).catch(function(e){
}),
Upvotes: 1