在BAE中使用mongoose操作mongodb

來源:互聯網
上載者:User

標籤:http   io   os   使用   ar   java   for   strong   資料   

在BAE中使用mongoose操作mongodb

  幾乎網上所有的使用mongoose的例子都是長串連的方式,因為nodejs本身機制的關係,使用長串連一定程度上會提高效能,但是bae的免費mongodb不支援長連結,之前也有很多人做了嘗試,比如斷開後捕捉錯誤,然後自動重連的方式,現在來看都不太成功,於是還是中規中矩的使用短連結的方式來做吧,這裡實現了一個串連開啟和關閉的託管。

mongoosekeeper.js

‘use strict‘;var mongoose = require(‘mongoose‘);var util = require("util");function MongooseKeeper() {    this.db = mongoose.createConnection();    this.open_count = 0;}MongooseKeeper.prototype.config = function(conf) {    // body...    var options = {        db: { native_parser: true },        server: {            poolSize:4        }    };    var constr = "";    if(process.env.MONGO_DB_STR){        constr = process.env.MONGO_DB_STR ;    }    else{        //‘mongodb://user:[email protected]:port/database‘        constr = util.format(‘mongodb://%s:%[email protected]%s:%d/%s‘, conf.userid,conf.password,conf.host,conf.port,conf.database);    }    this.dbUri = constr;    this.options = options;}MongooseKeeper.prototype.open =function() {    this.open_count++;    if(this.open_count ==1 && this.db.readyState == 0)    {                this.db.open(this.dbUri,this.options,function() {            // body...            console.log("db opened");        });    }}MongooseKeeper.prototype.close =function() {    this.open_count--;    if(this.open_count == 0 )    {        this.db.close(function(){            console.log("db closed");        });    }}MongooseKeeper.prototype.use = function(action,callback) {    //OPEN    var self = this;    self.open();    action.call(null,function() {        //CLOSE        console.log("正在訪問的資料庫請求量"+self.open_count);        self.close();        callback.apply(null, arguments);        //DONE        self =null;    })};exports = module.exports = new MongooseKeeper();

首先在應用啟動的時候,比如在app.js中,配置資料連線的等資訊

// 引用mongoosekeepervar mongoosekeeper =  require(‘./lib/mongoosekeeper‘);
```// 調用更新配置,這裡的配置可以去讀某個jsonmongoosekeeper.config({    "host": "192.168.57.186",    "database": "dbname",    "userid":"userid",    "password":"123456",    "port":27017});

定義Model

‘use strict‘;var mongoose = require(‘mongoose‘);var Schema = mongoose.Schema;var mongokeeper  = require(‘../lib/mongoosekeeper‘);var articleModel = function () {    var articleSchema = new Schema({        content     : String, //  發布內容        type        : Number, //        pictures    : [{url:String,width:Number,height:Number}], // 配圖        thumbnails  : [{url:String,width:Number,height:Number}], // 縮圖        tags        : [String], // 標籤        author      : String, //  發布人帳號        author_name : String, //  發布人名稱        create_date : { type: Date, default: Date.now }, //建立時間        meta        : {                        votes  : Number, //頂                        favs   : Number  //收藏                    }    });    //因為使用了createConnection 這裡要使用mongokeeper.db.model    //而不是mongoose.model    return mongokeeper.db.model(‘article‘, articleSchema);};module.exports = new articleModel();

在調用model的時候,使用 mongoosekeeper.use 方法封裝實際的調用即可

var express        = require(‘express‘),    router         = express.Router(),    mongoosekeeper =  require(‘../lib/mongoosekeeper‘),    articleModel   =  require(‘../models/articleModel‘);/* GET home page. */router.get(‘/‘, function(req, res) {    mongoosekeeper.use(queryArticle,function(err,list){        if(err){            throw err;        }        else{            res.render(‘index‘,{data:list});        }    }); });//proxy 參數即為mongoosekeeper.use的第二個參數function queryArticle(proxy){    var search = {} ; //擷取所有文章    var query = articleModel.find(search).limit(25);     query.sort(‘-create_date‘);    query.exec(proxy);}module.exports = router;

完整代碼

在BAE中使用mongoose操作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.