zoukankan      html  css  js  c++  java
  • mongoose 数据库操作


    使用mongoose 加入分页方法,临时还没发现什么更好的方法,我使用的方法是,直接在源代码中加入


    找到 node_modules/mongoose/lib/model.js打开这个文件。里面加入这段代码



    /**
     * author:gtt
     * updateTime:2014-5-3 
     */
    Model.execPageQuery = function find (currentPage,pageSize, conditions, fields, options, callback) {
    	 if ('function' == typeof conditions) {
       	    callback = conditions;
       	    conditions = {};
       	    fields = null;
       	    options = null;
       	  } else if ('function' == typeof fields) {
       	    callback = fields;
       	    fields = null;
       	    options = null;
       	  } else if ('function' == typeof options) {
       	    callback = options;
       	    options = null;
       	  }
    	//var countLine = 20;// 总行数
    	//var countPage = (countLine + pageSize-1 )/pageSize;// 总页数
    	var StartLine = (currentPage -1)*pageSize;
    	var m = this;
    	async.parallel([
            function(cb) {
            	m.count({},cb);
            },      
            function(cb) {
          	  if ('function' == typeof conditions) {
          		m.find({}).limit(pageSize).skip(StartLine).exec(cb);
          	  } else if ('function' == typeof fields) {
          		 m.find(conditions).limit(pageSize).skip(StartLine).exec(cb);
          	  } else if ('function' == typeof options) {
          		m.find(conditions,fields).limit(pageSize).skip(StartLine).exec(cb);
          	  }else{
          		m.find(conditions,fields,options).limit(pageSize).skip(StartLine).exec(cb);
          	  }
            }
        ], function(err,rs){
    		
    		var page = {};//总页数 总条数 集合
    		if('number' == typeof rs[0]){
    			page.total = rs[0];
    			page.rows =  rs[1];
    		}else{
    			page.total = rs[1];
    			page.rows =  rs[2];
    		}
    		callback(err,page);
    	});
    }
    调用方法:


    var assert = require('assert')
    var util=require('util');
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var ObjectId = mongoose.Types.ObjectId;
    
    
    
    mongoose.connect('mongodb://localhost:8888/test');
    mongoose.connection.on('error', function() {
    	console.error('connection error', arguments);
    });
    
    
    var PersonSchema = new Schema({
        name : String
      });
    
    var Person = mongoose.model('Person', PersonSchema,'Person');
    
    
    
    Person.execPageQuery(1,100,function(err,rel){
    	console.dir(rel);
    });



    成天都在实现这样的烂玩意,啥时候自己也搞一套牛逼的。


  • 相关阅读:
    配置Mysql远程访问
    mysql Access denied for user root@localhost错误处理备忘
    MsSql判断表是否有自增标识
    .net用NPOI生成Word表格
    TensorFlow-卷积
    Java中int与Integer的区别
    由经纬度坐标得到腾讯地图的瓦片/切片行列号
    vs code上配置Scala
    VMware虚拟机上配置CentOS联网
    使用PuTTy在CentOS下安装web.py与简单的文件传输
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5173107.html
Copyright © 2011-2022 走看看