Express / Mongoose项目中的HTTP Get和Post请求中缺少内容

时间:2017-06-05 21:42:35

标签: javascript node.js mongodb express mongoose

我有以下文件。我有一个recipe.js文件,其中概述了配方的Mongoose Schema和配方的注释。它的代码如下:

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});
};

*/

我还有一个user.js文件,其中概述了一个用户模型及其与其他模型/模式的关系。文件中的代码如下:

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);

这里是recipeRouter.js,我定义所有HTTP请求和路由的文件:

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;

现在,在某些时候我能够创建食谱并将它们存储在我的数据库中而没有任何问题。但现在发生这种奇怪的事情。

在这里,我发布了帖子请求,如下面的屏幕截图所示:enter image description here

但是由于一些奇怪的原因,每次我发出一个get请求时,我在json body请求中指定的键/值对都没有。每个配方对象现在只作为其中的_id。

enter image description here

任何人都可以帮助我吗?这看起来很奇怪。

1 个答案:

答案 0 :(得分:0)

您似乎只是错过了application/json Content-Type标题。

在Postman中,只需设置标题,如in this gif所示。