MongoDB
NodeJS - Express - MongoDB
Integration of MongoDB into NodeJS-Express environment:
0. Let assume that we have database 'my_db' already created.
1. $ npm install mongodb
2. /routes/index.js
/*jslint unparam: true*/
var express = require('express');
var router = express.Router();
var nodedump = require('nodedump').dump; //debugger: res.send(nodedump(req)).end();
//MongoDB
var MongoClient = require('mongodb').MongoClient;
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', { title: 'Express' });
});
/* MongoDB find() test */
router.get('/mdbfind', function (req, res) {
MongoClient.connect("mongodb://localhost:27017/my_db", function (err, db) {
if (err) {
res.send('MongoDB Error:<br>' + err).end();
} else {
db.collection('user').find().toArray(function (err, items) {
//res.json(items);
//res.send(nodedump(items)).end();
//console.log(JSON.stringify(items, null, 4));
var vdata = {
"title": 'List of users',
"items": items
};
res.render('mdbfind', vdata);
});
}
});
});
router.get('/mdbinsert', function (req, res) {
res.render('mdbinsert'); //input form
});
router.post('/mdbinsert', function (req, res) {
//get POST form variables
var user = req.body.user;
var pass = req.body.pass;
var ins;
if (user !== '' && pass !== '') {
ins = {"user" : user, "pass" : pass};
} else {
ins = null;
}
//insert into MongoDB
MongoClient.connect("mongodb://localhost:27017/my_db", function (err, db) {
if (err) {
res.send('MongoDB Error:<br>' + err).end();
} else {
if (ins !== null) {
db.collection('user').insert(ins);
}
}
});
res.render('mdbinsert'); //input form
});
module.exports = router;
3. /views/mdbfind.hjs --Hogan file
<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
<link rel='stylesheet' href='/stylesheets/style.css'>
</head>
<body>
<h1>Show all users</h1>
<ol>
<li style="list-style-type:none">USER -- PASS</li>
{{#items}}
<li start="1">{{user}} -- {{pass}}</li>
{{/items}}
</ol>
<br>
<br>
<br>
<a href="/mdbinsert">Insert new user!</a>
</body>
</html>
4. /views/mdbinsert.hjs - Insert form
<!DOCTYPE html>
<html>
<head>
<title>Insert into MongoDB</title>
<link rel='stylesheet' href='/stylesheets/style.css'>
</head>
<body>
<h1>Insert into MongoDB</h1>
<form action="/mdbinsert" method="POST">
User: <input type="text" name="user">
<br>Password: <input type="text" name="pass">
<br><br> <input type="submit" value="Insert">
</form>
<br>
<br>
<br>
<a href="/mdbfind">Show results (users)!</a>
</body>
</html>