nodejs如何使用mongo數據庫

首先,使用express創建一個基礎網站,

npm install express

生成網站

$ express  myapp

create : myapp
create : myapp/package.json
create : myapp/app.js
create : myapp/public
create : myapp/public/javascripts
create : myapp/public/images
create : myapp/public/stylesheets
create : myapp/public/stylesheets/style.css
create : myapp/routes
create : myapp/routes/index.js
create : myapp/views
create : myapp/views/layout.jade
create : myapp/views/index.jade

install dependencies:
    $ cd myapp && npm install

run the app:
    $ node app

安裝mongoose模塊

npm install  mongoose

mongoose官網 http://mongoosejs.com/

在express的routes/index.js文件裏,加入如下代碼

exports.index = function(req, res){
  var mongoose = require('mongoose'); 

  var db = mongoose.createConnection('localhost', 'test');

  var schema = mongoose.Schema({ name: 'string' }); 
  var User = db.model('User', schema);

  var kitty = new User({ name: 'Zildjian' }); 
  kitty.save(function (err) {
    if (err) // ...
    res.end('meow');
  }); 


  User.find({'name':'Zildjian'},function(err,docs){  
    res.render('index', { title: docs});
  }); 
}; 

打開網頁地址 http://localhost:3000/ 就能看到剛纔新增的數據庫記錄輸出了。

發佈了17 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章