Using Mongoose to manipulate MongoDB in Bae

Source: Internet
Author: User

Using Mongoose to manipulate MongoDB in Bae

Almost all of the examples on the web using mongoose are long-connected, because the relationship between the Nodejs itself mechanism, the use of long connections to some extent will improve performance, but Bae's free MongoDB does not support long links, many people have tried before, such as the disconnection after the catch error, And then automatically reconnect the way, now it is not very successful, so it is a good way to use the short link to do it, where a connection to open and close the hosting.

Mongoosekeeper.js

' Use strict '; var mongoose = require (' Mongoose '); var util = require ("util"); function Mongoosekeeper () {this.db = Mongoo    Se.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]:p ort/database ' constr = Util.format (' Mongodb://%s:%[emai    l 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,functi        On () {//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 ("The number of database requests being accessed" +self.open_count);        Self.close ();        Callback.apply (null, arguments);    Done self =null; })};exports = Module.exports = new Mongoosekeeper ();

First, when the application is started, such as in App.js, configure the data connection and other information

Reference Mongoosekeepervar Mongoosekeeper =  require ('./lib/mongoosekeeper ');
"//Call Update configuration, here the configuration can read a jsonmongoosekeeper.config ({    " host ":" 192.168.57.186 ",    " database ":" dbname ",    " UserID ":" userid ","    password ":" 123456 ",    " port ": 27017});

Define Model

When you call model, mongoosekeeper.use you can use the method to wrap the actual call

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});});    The/proxy parameter is the second parameter of Mongoosekeeper.use, function queryarticle (proxy) {    var search = {};//Get all articles    var query = Articlemodel.find (search). Limit (+);     Query.sort ('-create_date ');    Query.exec (proxy);} Module.exports = router;

Full code

Using Mongoose to manipulate MongoDB in Bae

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.