Hello world with MongoDB!

1

Objective: make a hello world with MongoDB in Node.js, which consists of saving an email and password in a BD called mi_bd.

Problem: I have a form with two input text for the email and user, and when I submit, the browser returns The data was saved correctly , but the console returns an error: the headers have already been sent .

What I'm doing: When I create a new project this one comes by default with this structure:

  • bin
  • node_modules
  • public
  • routes
    • index.js
    • users.js
  • views
  • app.js
  • npm-debug.log
  • package.json

In app.js I add this:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mi_esquema = new Schema({
  email: {type: String},
  password: {type: String}
});
var User = mongoose.model("User",mi_esquema);
mongoose.connect('mongodb://localhost/mi_bd', (err, res) => {
  if (err) {
    throw err;
    console.log("ERROR! Imposible establecer conexión a la DB");
  }
  else {
    console.log("Conexión OK a la DB");
  }
});

In routes / users.js I add this:

var mongoose = require('mongoose');
var User = mongoose.model("User");

router.post('/', function(req, res, next) {
  var user = new User({ email: req.body.email, password: req.body.password });
  user.save(function(){
    res.send("Los datos fueron guardados en la BD");
  });
});

I suspect that the error that the headers were already sent, is caused by the line:

var mongoose = require('mongoose');

that I put in routes / users.js. But if I remove it, the console tells me that mongoose is not defined, which is the mongoose of:

var User = mongoose.model("User")

And if I remove this last line, the console tells me that User is not defined (which is the User declared in the route).

Any ideas on how to solve this?

NOTES

  • I've already installed MongoDB and Mongoose.
  • I've based on this tutorial ; in which the folder tree is different from mine, so in the tutorial the path goes in app.js, and not in users.js as in my case.

Greetings!

    
asked by George Berkeley 03.02.2017 в 05:13
source

1 answer

1

Why do you use a middleware for a normal route mapping? It is wrong to do so. Middlewares are designed to intercept a route and execute code before executing the function associated with it. Your code should look like this (here I am using Promesas but you can follow with callbacks if you prefer)

router.post('/', function(req, res) {
  let { body } = req;
  User
    .create(body)
    .then((doc) => {
      // luego de crear, mongoose te devuelve el
      // documento creado por si lo necesitas
      res.jsonp({
        user: doc,
        message: 'Usuario creado'
      });
    });
});

Another important point is that you are saving the passwords as plain text . This should always be avoided because anyone who has access to the database has access to passwords and this should not be the case. Mongoose allows you to create middlewares or hooks that will be executed before or after an event. You can take advantage of this feature to hash passwords before saving the document.

User.pre('save', function (next) {
  let salt = bcrypt.genSaltSync(10);
  this.password = bcrypt.hashSync(this.password, salt);
  next();
});

The previous code hashea with bcrypt the password of every document User that is going to be created.

    
answered by 03.02.2017 в 08:15