nodejs操作mongodb简单实例

数据库操作

mongo;

use test3;

db.users.insert({"name":"aaa","email":"[email protected]"});

nodejs代码编写

新建test3目录,编辑如下文件:

package.json

{
    "name": "application-name",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node app.js"
    },
    "dependencies": {
        "express": "3.4.4",
        "jade": "*",
        "mongodb": "*",
        "monk": "*"
    }
}

app.js

var express = require(‘express‘);
var routes = require(‘./routes‘);
var user = require(‘./routes/user‘);
var http = require(‘http‘);
var path = require(‘path‘);
var mongo = require(‘mongodb‘);
var monk = require(‘monk‘);
//
var db = monk(‘localhost:27017/test3‘);
//
var app = express();
//all environments
app.set(‘port‘, process.env.PORT || 3000);
app.set(‘views‘, path.join(__dirname, ‘views‘));
app.set(‘view engine‘, ‘jade‘);
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.get(‘/users‘, user.list);
//create server
http.createServer(app).listen(app.get(‘port‘), function() {
    console.log(‘Express server listening on port ‘ + app.get(‘port‘));
});
//hello world
app.get(‘/hello‘, routes.hello);
//user list
app.get(‘/userlist‘, routes.userlist(db));
//new user
app.get(‘/newuser‘, routes.newuser);
//add user
app.post(‘/adduser‘, routes.adduser(db));

routes/index.js

exports.index = function(req, res) {
    res.render(‘index‘, {title: ‘Express‘});
}
exports.hello = function(req, res) {
    res.render(‘hello‘, {title: ‘hello, world.‘});
}
exports.userlist = function(db) {
    return function(req, res) {
        var collection = db.get(‘users‘);
        collection.find({}, {}, function(e, docs) {
            res.render(‘userlist‘, {
                ‘userlist‘: docs
            });
        });
    };
}
exports.newuser = function(req, res) {
    res.render(‘newuser‘, {title: ‘Add New User‘});
}
exports.adduser = function(db) {
    return function(req, res) {
        var username = req.body.username;
        var useremail = req.body.useremail;
        var collection = db.get(‘users‘);
        collection.insert({
            "name": username,
            "email": useremail
        }, function(err, doc) {
            if (err) {
                res.send(‘there was a problem adding the information to the db.‘);
            } else {
                res.location(‘userlist‘);
                res.redirect(‘userlist‘);
            }
        });
    };
}

routes/user.js

exports.list = function(req, res) {
    res.send(‘respond with a resource‘);
}

views/index.jade

extends layout

block content
    h1= title
    p Welcome to #{title}

views/hello.jade

extends layout

block content
    h1= title
    p Welcome to #{title}

views/userlist.jade

extends layout

block content
    h1.
        User List
    ul
        each user, i in userlist
            li
                a(href="mailto:#{user.email}")= user.name

views/newuser.jade

extends layout

block content
    h1= title
    form#formAddUser(name="adduser",method="post",action="/adduser")
        input#inputUserName(type="text",placeholder="username",name="username")
        input#inputUserEmail(type="text",placeholder="useremail",name="useremail")
        button#btnSubmit(type="submit") submit

views/layout.jade

doctype html
html
    head
        title= title
        link(rel=‘stylesheet‘, href=‘/stylesheets/style.css‘)
    body
        block content

软件运行

cd test3

npm install

node app.js

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。