Carlitos
Carlitos

Reputation: 9

POST going directly to the catch error and not saving data using mongoose, MongoDB, NodeJS, and Express

I already tried some possible solutions and even created and wrote the code again but I am still getting errors. I have created a diminute version of my whole code which connects to the database using Mongoose but after the Schema is created and I import the model in places-controllers my data that I write in POSTMAN goes directly to:

FYI: In this case I want POST request from createPlace to properly work.

Data entry: URL: http://localhost:5000/api/places/

{
    "title": "Punta Arena Stfdsfdsfsdfop",
    "description": "One stop Stop. Does not have tr12affic lights.",
    "busrespect": "12ysdfdsfsfes",
    "address": "Avenida Solunna",
    "creator": "52peru soiflsdjf36"
}

OUTPUT:

{
    "status": "error caught"
}

which is what I told the program to define if the try did not work.

IN app.js I have the following code:

const express= require('express');

const mongoose = require('mongoose');

const bodyParser = require('body-parser');
const placesRoutes = require("./routes/places-routes");

const HttpError = require ("./models/http-error");
const app = express();

app.use(bodyParser.json());

app.use('/api/places', placesRoutes);

app.use((req, res, next) => { 
    const error= new HttpError('Route not available. Try something different?', 404);
    throw error;
});

app.use((error, req, res, next) =>{
    if (res.headerSent) {
        return next(error);
    }
    res.status(error.code || 500)
    res.json({message: error.message || "An unknown error occured! Sorry" });
});


url = '<mongo_url>'

mongoose.connect(url, {useNewUrlParser: true}).then(()=>{
    console.log("Connected to database")
    app.listen(5000);
}).catch(erro => {
    console.log(erro)
});

In places-routes.js I have the following code:

const express = require('express');

const {check} = require('express-validator')

const placesControllers=require('../controllers/places-controllers');

const router = express.Router();

router.get('/:pid', placesControllers.getPlaceById );

router.get('/user/:uid',placesControllers.getPlacesByCreatorId );

router.post('/' ,[
  check('title')
    .not()
    .isEmpty(),
  check('description').isLength({ min: 5 }),
  check('address')
    .not()
    .isEmpty()
],
placesControllers.createPlace);
 
router.patch('/:pid', [
  check('title')
    .not()
    .isEmpty(),
  check('description').isLength({ min: 5 })
] , placesControllers.updatePlace );

router.delete('/:pid', placesControllers.deletePlace);

module.exports=router;


In places-controllers.js I have the following code:

const HttpError = require('../models/http-error');

const { validationResult } = require('express-validator');
//const getCoordsForAddress= require('../util/location');
const BusStop = require('../models/place');

let INITIAL_DATA = [
    {
        id: "p1",
        title: "Samoa Stop",
        description: "My first bus stop in Lima",
        //location: {
           // lat: 40.1382,
           // lng:-23.23
       // },
        address: "Av. La Molina interseccion con calle Samoa",
        busrespect: "yes",
        creator: "u1"
        }
];

const getPlaceById = (req, res, next) => {
    const placeId = req.params.pid // Accessing the p1 in pid URL scrapping {pid:'p1'}  
    const place= INITIAL_DATA.find(p => { //find method goes over each element in the array, the argument p represents the element where find loop is
      return p.id ===placeId
    });
  
    if (!place) {
      const error= new HttpError('No bus stop found for the provided ID.', 404);
      throw error; 
  
    }
  
    res.json({place: place});
  };

const getPlacesByCreatorId = (req, res, next)=> {
    const userId = req.params.uid;

    const places = INITIAL_DATA.filter(p=>{ //filter to retrieve multiple places, not only the first one
        return p.creator ===userId;
    });
    
    if (!places || places.length===0) {
        return next(
          new HttpError('Could not find bus stops for the provide user id', 404)
          );
    }

    res.json({places});
};

const createPlace = async (req, res,next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()){
        return next(new HttpError ('Invalid bus stop please check your data', 422));
    }

    //const { title, description, busrespect, address, creator } = req.body; //erased location for now.
  
   /*  let place = new BusStop({
      title: req.body.title,
      description: req.body.description,
      busrespect: req.body.busrespect,
      address : req.body.address,
      creator: req.body.creator
  })

  awaitplace.save()

  .then(response=>{
      res.json({
          message : "Employee added sucessfully!"
      })
  })

  .catch(err=>{
      res.json({
          message : "An error has occured!"
      })
  })
} */
const { title, description, busrespect, address, creator } = req.body;
     try {
        await BusStop.create({
         title:title,
         description: description,
         busrespect:busrespect,
         address: address,
         creator: creator
       });
       res.send({status: "ok"});
     } catch(error) {
       res.send({status:"error caught"});
     }
   };

  const updatePlace = (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()){
        console.log(errors);
        throw new HttpError ("Invalid inputs passed, please check your data ", 422);
    };

    const { title, description } = req.body;
    const placeId = req.params.pid;
  
    const updatedPlace = { ...INITIAL_DATA.find(p => p.id === placeId)};
    const placeIndex = INITIAL_DATA.findIndex(p => p.id === placeId);
    updatedPlace.title = title;
    updatedPlace.description = description;
  
    INITIAL_DATA[placeIndex] = updatedPlace;
  
    res.status(200).json({place: updatedPlace});
  };

const deletePlace = (req, res, next) => {
    const placeId = req.params.pid;
    if (!INITIAL_DATA.find(p=> p.id ===placesId))
       throw new HttpError('Could not find a bus stop for that ID ')

    INITIAL_DATA = INITIAL_DATA.filter(p=> p.id !== placeId)
    res.status(200).json({message: 'Deleted Place'});
};


exports.getPlaceById= getPlaceById;
exports.getPlacesByCreatorId = getPlacesByCreatorId;
exports.createPlace = createPlace;
exports.updatePlace = updatePlace;
exports.deletePlace = deletePlace;

Inside models folder I have two files: http-error.js which has this code:

class HttpError extends Error {
    constructor(message, errorCode) {
        super (message); 
        this.code = errorCode;
    }
}

module.exports = HttpError;

The other file inside is the schema which is place.js

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const placeSchema = new Schema({
    title: {
      type: String
    },
    description: {
      type: String
    },
    address: {
      type: String
    }, 
    busrespect: {
      type: String
    },
    creator: {
      type: String
    }
},
)

const BusStop = mongoose.model('BusStop', placeSchema)

module.exports= BusStop

Summary: somewhere in the try catch part from createPlace something is going wrong since my data entry is always going to the error status I indicated in that part.

Upvotes: 0

Views: 210

Answers (0)

Related Questions