Search code examples
javascriptnode.jsmongodbexpressmongoose

Express gives the same response even with different input-values in MongoDB


I'm new learning Express and MongoDB. I'm following an Udemy course, and I'm sure that my code is exactly the same.

My problem:

When I post some data to a MongoDB collection, it works as expected. But when I try to add a new value, it works, but inserts the same value that the first post, even when the inputs values are differents.

Here is some of my code:

###pacienteControllers.js###

const Paciente = require('../models/Paciente');

exports.newClient = async (request, response, next) =>{
   const paciente = new Paciente(request.body);
   try {
      await paciente.save();
      response.json({mensaje: 'El cliente se agregó correctamente'});
   } catch (error) {
      console.log(error);
      next();
   }
}

###routes/index.js:###

const express = require('express');
const router = express.Router();
const PacienteController = require('../controllers/PacienteControllers');

module.exports = () =>{
   
   router.get('/', () =>{
      console.log("Petición enviada");
   })

   router.post('/pacientes',
      PacienteController.newClient
   )

   return router;
}

###index.js:###

const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes/index');
const bodyParser = require('body-parser');
const server = express();

mongoose.Promise = global.Promise;
mongoose.connect('mongodb+srv://?retryWrites=true&w=majority', {
   useNewUrlParser: true,
   useUnifiedTopology: true,
   useFindAndModify: false 
});

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: true}));

server.use('/', routes());

server.listen(4000, () => console.log("servidor funcionando"));

Note: username and password are correct values, just censured for security reasons.

I would like to know why is this happening. ¿Is there some kind of cache?

TESTS

I'm using Postman to do posts tests. When I do the first post I get the message: El cliente se agregó correctamente meaning that the client was added successfuly.

But when I try to add a new register to the database, I get the same message but, when I update the database to see new changes, I get the new register but with the same values of the first post.

EDIT

Added server.use(bodyParser.json()); but still getting same results.


Solution

  • You only import routes folder but not index.js file in your root file index.js so import as

    const routes = require('./routes/index');
    

    You are sending message in JSON object But you didn;t use middleware in index.js so add

    server.use(bodyParser.JSON());
    

    Your routes and controller can be merged like this: In your routes/index.js file add this code:

    const express = require('express');
    const router = express.Router();
    const Paciente = require('../models/Paciente');
    
    router.post('/pacientes', async (req, res) => {
      const paciente = new Paciente(req.body);
      try {
         const saveData = await paciente.save();
         res.json({ message: "El cliente se agregó correctamente" });
         }
           catch ( err ) {
             res.json({ message: err }); 
           }
         });
    
     //You can view all the data from here
       router.get('/', async (req,res) => {
        const data  = await Paciente.find();
         try {
           res.json(data);
         }  catch( err ) {
             res.json({ message: err })
            }
         });
     module.exports = router;
    

    You can now remove pacienteController.js file