首页 > 代码库 > nodejs操作mongodb简单实例

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 environmentsapp.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 onlyif (‘development‘ === app.get(‘env‘)) {    app.use(express.errorHandler());}//app.get(‘/‘, routes.index);app.get(‘/users‘, user.list);//create serverhttp.createServer(app).listen(app.get(‘port‘), function() {    console.log(‘Express server listening on port ‘ + app.get(‘port‘));});//hello worldapp.get(‘/hello‘, routes.hello);//user listapp.get(‘/userlist‘, routes.userlist(db));//new userapp.get(‘/newuser‘, routes.newuser);//add userapp.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 layoutblock content    h1= title    p Welcome to #{title}

views/hello.jade

extends layoutblock content    h1= title    p Welcome to #{title}

views/userlist.jade

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

views/newuser.jade

extends layoutblock 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 htmlhtml    head        title= title        link(rel=‘stylesheet‘, href=http://www.mamicode.com/‘/stylesheets/style.css‘)    body        block content

软件运行

cd test3

npm install

node app.js

nodejs操作mongodb简单实例