Tute 11: MongoDB, express, saving data in database - ariffira/node-basic GitHub Wiki
This tute will explain:
- how to connect mongodb easily in nodejs app/ express app
- creating schemas and model(using mongoose)
- data storing/saving
Step 01: Connecting MongoDB using mongoose to your express APP:
// add mongoose package
const mongoose = require('mongoose');
Connect mongoose:
mongoose.connect('mongodb://localhost/yourDataBaseName');
Step 02: Lets create a Schema for our user model for the registration form
models/user.js
add this code their:
// add mongoose package
const mongoose = require('mongoose');
// add mongoose Schema object
const Schema = mongoose.Schema;
//create a new Schema for user
const userSchema = new Schema({
firstname: String,
lastname: String,
email: String,
password: String,
createdAt: Date
});
// make new user Schema as a model for use
// model(function name for model, schema data)
const User = mongoose.model('User', userSchema);
// make it usable to the application
module.exports = User;
So far model is ready for action ;)
Step 03: Use your model in route and save data on registration
// add model user in app.js
const User = require('./models/user');
// posting resgitration form data to save in MongoDB
app.post('/registration', (req, res) => {
let postData = req.body;
console.log(postData);
// create a new user object as like your user schema
let newUser = new User({
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
password: req.body.password,
createdAt: Date.now()
});
// Save the user to database
newUser.save(err => {
if(err) throw err;
console.log('A new User Saved to Database!');
});
res.redirect('/signin');
});
So now you can save your data... great. Check it using Robo mongo or from terminal.