Express with Mongo
Prepare install mongodb
Before starting programming, we need some steps.
- Install mondodb
- Start mongod
- Create db(from mongo client)
Install
Please other entry(NodeJS Mongo Basic)
Start
Please prepare directory to save mongodb files.
There will be huge file as first preparation. Mongo prepare huge blank data file at first.
mongod --dbpath ./data
data is mongo data directory.
Create
Let’s create db in your mongo
To connect mongo, we can use mongo command
mongo
If you already started mongod, you can connect this mongod
show dbs
You can see db list
use mydata
mydata is db name. That’s all for preparation.
Install mongoose in your Express project
Add package to package.json
"mongoose" : "*"
Add mongoose and install
npm install
Mongo programming
I prepared two files.
One is a common connection file. The other is schema definition file.
Everytime I added new model, I create new schema definition file.
dbconfig.js
This is for connection
// // Database connection // // Database connect var mongoose = require('mongoose'); exports.mongoose = mongoose; var mongoOptions = { db: { safe:true }}; mongoose.connect('mongodb://localhost/mydata', mongoOptions, function(err, res){ if (err) { console.log('ERROR connecting to:localhost ' + err); } else { console.log('Successfully connected'); } }); // host/databasenam
Connect mydata db in this case.
schema(user)
Prepare schama and some operations in same file.
var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var SALT_WORK_FACTOR = 10; var Schema = mongoose.Schema; var userSchema = new Schema({ name: { type: String, required: true, index: {unique: true}}, email: { type: String, required: true, index: {unique: true}}, password: { type: String, required: true } }); //Bcrypt middleware userSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) return next(); bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) { if (err) return next(err); bcrypt.hash(user.password, salt, function(err, hash) { if (err) return next(err); user.password = hash; next(); }); }); }); //Password verification userSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; // Export admin model var userModel = mongoose.model('User', userSchema); exports.userModel = userModel;
Add password verification too.
Use mongo
Let’s use mongo in main program.
This example is route program not main.
var express = require('express'); var userRoutes = express.Router(); var db = require('../dbconfig'); // Actually, it should be in app.js var userdb = require('../user'); // user.js(schema) userRoutes.get('/member/profile/:id', function(req, res, next) { var id = req.params.id; userdb.userModel.findOne({ '_id': id }, function(err, data) { if (err) { console.log(err); next(err); } res.render('profile', {user: data.name}); } }); });