Monday, 5 June 2017

my router for my express and mongoose code keeps getting a TypeError when I try to run app.js

I am creating a website using mongoose and express.

Whenever I try to run app.js, I keep getting this error:

  req.next = next;
           ^

TypeError: Cannot create property 'next' on string '/addrecipe'

The problem seems to be in the file where I define my route. Here is the code for that file:

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


router = express.Router();

router.use(bodyParser.json());

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



router.get('/showrecipes', (req, res) => {
  Recipe.find({}, (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);
    })
});



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




//// here is the code that isn't working

router('/addrecipe')

    .post(verification.checkIfUserExists, (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('/showrecipes/:recipeId')

    .put(verification.checkIfUserExists, (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)
    })
    })

// It's working, thank god

    .delete(verification.checkIfUserExists, (req, res) => {

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

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

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

    })

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

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

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

// test this

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



/*

router.post('/:dishid/addcomment', function(req, res, next){
  let newComment = new Comment({
    rating: req.body.rating,
    comment: req.body.comment,
    postedBy: postedBy,
    date: Date.now()
  });

});

*/

module.exports = router;

For reference, here is also the code for my app.js file:

let express = require('express');
let mongoose = require('mongoose');
let path = require('path');
let bodyParser = require('body-parser');
let recipeRouter = require('./routes/recipeRouter');
let userRouter = require('./routes/userRouter');
let bcrypt = require('bcrypt');
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
let config = require('./config');
let logger = require('morgan');
let cookieParser = require('cookie-parser');

mongoose.connect(config.mongoUrl);

let db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function () {
    // we're connected!
    console.log("Connected correctly to server");
});

const app = express();

const port = 3000;

app.listen(port);



let User = require('./models/user');
app.use(passport.initialize());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.use(cookieParser());



app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json());

app.set('views', path.join(__dirname, 'views'));

app.use('/users', userRouter);
app.use('/recipes',recipeRouter);

app.get('/', function(req, res){
  res.send('Hey, this is your database!')
});

app.use((req, res, next) => {
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
});

if (app.get('env') === 'development') {
    app.use((err, req, res, next) => {
        res.status(err.status || 500);
        res.json({
            message: err.message,
            error: err
        });
    });
}

app.use((err, req, res, next) =>{
    res.status(err.status || 500);
    res.json({
        message: err.message,
        error: {}
    })
});




module.exports = app;



via T-Dot1992

No comments:

Post a Comment