recipeData.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const Recipe = require("../models/recipe");
  2. const Merchant = require("../models/merchant");
  3. module.exports = {
  4. //POST - creates a single new recipe
  5. //Inputs:
  6. // req.body.name: name of recipes
  7. // req.body.price: price of the recipe
  8. // req.body.ingredients: array of ingredients (object) in recipe
  9. // id: id of ingredient
  10. // quantity: quantity of ingredient in recipe
  11. //Returns the newly created recipe
  12. createRecipe: function(req, res){
  13. if(!req.session.user){
  14. req.session.error = "Must be logged in to do that";
  15. return res.redirect("/");
  16. }
  17. let recipe = new Recipe({
  18. merchant: req.session.user,
  19. name: req.body.name,
  20. price: Math.round(req.body.price * 100),
  21. ingredients: req.body.ingredients
  22. });
  23. Merchant.findOne({_id: req.session.user})
  24. .then((merchant)=>{
  25. merchant.recipes.push(recipe);
  26. merchant.save()
  27. .catch((err)=>{
  28. return res.json("Error: unable to save recipe");
  29. });
  30. })
  31. .catch((err)=>{
  32. return res.json("Error: unable to retrieve user data");
  33. })
  34. recipe.save()
  35. .then((newRecipe)=>{
  36. return res.json({});
  37. })
  38. .catch((err)=>{
  39. console.log(err);
  40. return res.json("Error: unable to save new ingredient");
  41. });
  42. }
  43. }