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!