nodejs操作mongodb簡單一實例

來源:互聯網
上載者:User

標籤:

資料庫操作

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 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=‘/stylesheets/style.css‘)    body        block content
軟體運行

cd test3

npm install

node app.js

nodejs操作mongodb簡單一實例

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.