Mongodb在nodejs中的初步嘗試

此篇僅介紹mongodb的安裝與使用,可在上一篇 【nodejs和express 初步學習之(get,post接口)】 的基礎之上進一步學習。

1. 安裝mongoose模塊

npm install mongoose --save

2. 加載mongoose核心模塊

var mongoose = require(‘mongoose’);

3. 指定連接本地數據庫端口和數據庫名

mongoose.connect(‘mongoose://localhost:27017/Test’);

4. 打開連接

var db = mongoose.connection;

5. 連接提示信息(成功/失敗)

db.on(‘error’ , function(){
    console.log(‘數據庫連接失敗’);
});
db.on(‘open’ , function(){
    console.log(‘數據庫連接成功’);
});

6. 創建數據庫中的集合 (table)

var  Schema = mongoose.Schema;
var  tableSchema = new Schema({
    name : String,
    age : Number,
    sex : String,
    address : String
});

7. 創建集合模板

var  Table = mongoose.model(‘tables’ , tableSchema);

8. 實例化集合

var cl = new Table({
    name:'張三',
    age:18,
    sex:'male',
    address:'上海市'
});

9. 存儲

cl.save();  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章