Monday 5 June 2017

content is missing from HTTP Get and Post requests in Express/Mongoose project

I have the following files. I have a recipe.js file which outlines the Mongoose Schema for a recipe and the comments for a recipe. The code for it goes as follows:

const express = require('express');
const mongoose = require('mongoose');
const User = require('../models/user');

let Schema = mongoose.Schema;

let commentSchema = Schema({

  rating: {
    type: Number,
    // required: true,
    min: 1,
    max: 5,
  },

  recipeItem: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Recipe'
  },

  comment: {
    type: String,
     // required: true
  },

  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },

  likedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },

 favouredBy: {
    type: mongoose.Schema.Types.ObjectId
 }
});

let Comment = mongoose.model('Comment', commentSchema);

let recipeSchema = Schema({

  name: {
    type: String,
    required: true
  },

  description: {
    type: String,
  },

  steps: {
    type: String,
    required: true,
  },

  ingredients: {
    type: Array,
    required: true
  },

  comments: [commentSchema],

  category: {
    type: String,
    required: true,
  },

  postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }

});

/// So I learnt that by defining the string as "Recipe" in the model function, I will have to lower case it
/// and pluralize it when I use it with res.json and other such things (i.e. "Recipe" => recipes).

let Recipe = mongoose.model('Recipe', recipeSchema);

module.exports = Recipe;
module.exports = Comment;

/// refactor this so that these are in the router, not in the models file

/*

module.exports.getRecipeByName = (name, callback) => {
  let nameQuery = {name: name};
  Recipe.findOne(nameQuery, callback);
};

module.exports.getRecipesByCategory = (category, callback) => {
  Recipe.find({'category': category});
};

*/

I also have a user.js file where I outline a a User model and the relation it has to the other models/schemas. The code in the file is as follows:

const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const passportLocalMongoose = require('passport-local-mongoose');
const passport = require('passport');

let Schema = mongoose.Schema;


let User = Schema({

  name: {
    type: String
  },

  // The passport plugin already inputs username and password into our Schema

  username: {
    type: String,
    unique: true,
    required: true
  },

   password: {
   type: String,
   required: true,
   },



  profilePic: {
    type: String
  },

  email: {
    type: String,
    unique: true,
    required: true
  },



  admin: {
    type: Boolean,
      defualt: false
  },

  usersRecipes: [{type: Schema.Types.ObjectId, ref:'Recipe'}],

  userComments: [{type: Schema.Types.ObjectId, ref: 'Comment'}],

  usersFavouriteRecipes: [{type: Schema.Types.ObjectId, ref: 'Recipe'}],

  usersLikedRecipes: [{type: Schema.Types.ObjectId, ref: 'Recipe'}]



});



let options = ({missingPasswordError: "Incorrect password, try again"});

User.plugin(passportLocalMongoose, options);

module.exports = mongoose.model('User', User);

And here is recipeRouter.js, the file where I define all the HTTP requests and routes:

const express = require('express');
const passport = require('passport');
const Recipe = require('../models/recipe');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const verification = require('../verification');
const Comment = require('../models/recipe');

// I temporarily removed verification.checkIfUserExists to see if all this database stuff works


router = express.Router();

router.use(bodyParser.json());

router.get('/', (req, res) => {
  res.json('Here are the recipes!')
});



router.get('/showrecipes', (req, res) => {
  Recipe.find({}).populate('Comment').exec((err, recipes) => {
      if (err) throw err;
      res.json(recipes);
  })
});


router.get("/showrecipes/:recipeId", (req, res) => {
    let nameQuery = {_id: req.params.recipeId};

    Recipe.findOne(nameQuery, (err, recipes) => {
        if (err) throw err;

        res.json(recipes);
    })
        //// Don't know if this is correct
        .populate('comment.recipeItem');
});


router.get('/showrecipes/category/:categoryname', (req, res) => {

    let nameQuery = {category: req.params.categoryname};

    Recipe.find(nameQuery, (err, recipes) => {
        if (err) throw err;

        res.json(recipes);
    });
});


router.post('/addrecipe', (req, res, next) => {

  Recipe.create({
      name: req.body.name,
      description: req.body.description,
      steps: req.body.steps,
      ingredients: req.body.ingredients,
      category: req.body.category
  }, (err, recipes) => {
    if (err) throw err;


    res.json(recipes);
  });
});

// See if this works

router.put("/showrecipes/:recipeId", (req, res) => {

        let query = {_id: req.params.recipeId};


    Recipe.findByIdAndUpdate(query, {
        $set: req.body
    }, {
        new: true
    }, (err, recipe) => {
        if (err) throw err;
        res.json(recipe)
    })
});


    router.delete("/showrecipes/:recipeId", (req, res) => {

        let query = {_id: req.params.recipeId};

        Recipe.findByIdAndRemove(query, (err, recipe) => {
            if (err) throw err;

            res.send('Recipe was succesfully deleted');
        })

    });

    router.get("/showrecipes/:recipeId", (req, res) => {
        let nameQuery = {_id: req.params.recipeId};

        Recipe.findOne(nameQuery, (err, recipes) => {
            if (err) throw err;

            res.json(recipes);
        })

            .populate('comments')

            .exec((err) => {
                if (err) throw err;
            })
    });

    router.post("/showrecipes:/:recipeId/addcomment", (req, res, next) => {

        Comment.create({
            rating: req.body.rating,
            comment: req.body.comment,
            postedBy: postedBy,
            date: Date.now(),
            recipeItem: recipeId
        })


    });


router.get('/showrecipes/byuser/:username', (req, res) => {

    let query = {postedBy: req.params.username};

    Recipe.find(query, (err, recipes) => {
        if (err) throw err;
        res.json(recipes)
    })

});



module.exports = router;

Now, at some point I was able to create recipes and store them in my database without a problem. But now this weird thing happens.

Here, I make my post request as you can see in the screenshot below:enter image description here

But for some strange reason, everytime I make a get request, none of the key/value pairs I specified in my json body request are there. Each recipe object now only as the _id in it.

enter image description here

Can anyone help me? This just seems so weird.



via T-Dot1992

No comments:

Post a Comment