Hi I am trying to make a registration form and i want to store data to MongoDB with node.js and from node.js I want to request an HTML form the email and password and then store that data to MongoDB.
Anyone know how?
To get info from the form using mongoose(MongoDB) and node.js you do:
const mongoose = require('mongoose');
mongoose.connect(mongoString, { useNewUrlParser: true, useUnifiedTopology: true });
const Schema = mongoose.Schema;
const userSchema = new Schema({
email: String,
password: String
});
const User = mongoose.model('users', userSchema);
app.post('/register', async (req, res, next) => {
const user = await User.findOne({
email: req.body.email
})
if (user) {
res.redirect('/register');
} else {
bcrypt.genSalt(10, function (err, salt) {
if (err) return next(err);
bcrypt.hash(req.body.password, salt, function (err, hash) {
if (err) return next(err);
new User({
email: req.body.email,
password: hash
}).save()
req.flash('error', 'Account made, please log in.');
res.redirect('/login');
});
});
}
});