• nodejs操作mongodb简单实例


    数据库操作

    mongo;

    use test3;

    db.users.insert({"name":"aaa","email":"aaa@123.com"});

    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

  • 相关阅读:
    POJ 1035-Spell checker(字符串)
    No valid host was found
    Does anyone successfully use USB drive in Windows7 guest?
    iptables 问题
    openstack kilo版本控制节点异常流量分析
    openstack 控制节点大流量对外发包,nf_conntrack,table full droping packets
    Error: rpmdb open failed
    openstack message queue
    POJ 1700 经典过河问题(贪心)
    树莓派遥控船项目计划
  • 原文地址:https://www.cnblogs.com/feilv/p/4195448.html
Copyright © 2020-2023  润新知