Categories: Uncategorized

[Javascript][Node.js][express]Connection with mongodb

I’ll make a program which save and read data with mongodb. At first I’ll make template using express.
$express -e firstapp

   create : firstapp
   create : firstapp/package.json
   create : firstapp/app.js
   create : firstapp/public
   create : firstapp/public/javascripts
   create : firstapp/public/images
   create : firstapp/public/stylesheets
   create : firstapp/public/stylesheets/style.css
   create : firstapp/routes
   create : firstapp/routes/index.js
   create : firstapp/routes/user.js
   create : firstapp/views
   create : firstapp/views/index.ejs

   install dependencies:
     $ cd firstapp && npm install

   run the app:
     $ node app
$npm install
$npm install mongose
Next is developing model which connects mongodb.
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/mongotest');

function validator(v) {
    return v.length > 0;
}

var Post = new mongoose.Schema({
    ua    : { type: String, validate: [validator, "Empty Error"] },
    created : { type: Date, default: Date.now }
});

exports.Post = db.model('Post', Post);

It can connect mongodb. Next is routing part.
/*
 * GET home page.
 */
var model = require('../model');
var Post = model.Post;

exports.index = function(req, res) {
    Post.find({}, function(err, items) {
        res.render('index', { title: 'Entry List', items: items , num: items.length, ua : JSON.stringify(req.headers['user-agent']) })
    });
};

exports.create = function(req, res){
    console.log(req.body);
    var newPost = new Post(req.body);
    newPost.save(function(err){
        if (err) {
            console.log(err);
            res.redirect('back');
        } else {
            res.redirect('/');
        }
    });
};
Add route to app.js.
/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.post('/create', routes.create);
//app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
The remaining thing is making top view.
<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <form method="POST" action="/create">
        <input type="hidden" name="ua" value="<%= ua %>">
        <input type="submit" value="Post" text="New Entry">
    </form>
    <br />
    <h2>Num Access : <%= num %></h2>
    <table border="1">
        <% items.forEach(function(item){ %>
            <tr>
                <td><%= item.created %></td>
                <td><%= item.ua %></td>
            </tr>
        <% }) %>
    </table>
  </body>
</html>

That’s all.
and input “node app.js”
zuqqhi2