一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

node.js基于mongodb的搜索分页示例

时间:2017-03-01 编辑:简简单单 来源:一聚教程网

mongodb模糊查询并分页

1.建立数据库

代码如下:

 

 代码如下 复制代码

varmongoose = require('mongoose');

varshortid = require('shortid');

varSchema = mongoose.Schema;

 

varIndexDataSchema =newSchema({

  _id: {

    type: String,

    unique:true,

    'default': shortid.generate

  },

  type: String,

  city: String,

  name:string,

  value: [{name: String, value: String}],

  create: {type: Date,default: Date.now},

  expand: String

});

 

IndexDataSchema.statics = {

  defaultSort: {'create': 1},

  defaultOptions: {'pageSize': 0}

 

};

 

 

varIndexData = mongoose.model('IndexData', IndexDataSchema);

 

module.exports = IndexData;

 

页面布局 这里只需要搜索框和搜索按钮,再点击按钮时,执行search()方法并发送请求

代码如下:

 

 代码如下 复制代码

          

          

        

        

 

2.到数据库查找并返回相应内容

 

 代码如下 复制代码

varformidable = require("formidable");

 varcommon = require('./common');

 varpath = require("path");

 varfs = require('fs');

 varpath = require('path');

 varguid = require('guid');

 varshortid = require('shortid');

  

 varAuctionHouse = require('./db/IndexData');

 

 

varfuns = {

 getList:function(collectionName, req, res, next) {

   varmainObj = transformCollctionName(collectionName);

   if(!mainObj) {

     next();

   }

   varoptions = req.query;

   varsort = options.sort || mainObj.defaultSort;

   varpageSize = options.pageSize || mainObj.defaultOptions.pageSize;

   varcurrentPage = options.currentPage || 1;

   varcondition = options.condition || {}

    

   //此部分为查找条件

   mainObj.find(condition).sort(sort).skip((currentPage - 1) * pageSize).limit(pageSize).exec(function(err, docs) {

     if(err) {

       next(err);

     }

     returnres.json(common.returnData(true, docs));

   })

 },

 countList:function(collectionName, req, res, next) {

   varmainObj = transformCollctionName(collectionName);

   if(!mainObj) {

     next();

   }

   varcondition = req.query.condition || {}

   mainObj.find(condition).count().exec(function(err, docs) {

     if(err) {

       next(err);

     }

     returnres.json({'count': docs});

   })

 },

 HandleEvent:function(collectionName, actionsName, req, res, next) {

   varmainFuns = getCollctionFuns(collectionName)

   if(!mainFuns) {

     next();

   }

   varfun = mainFuns[actionsName];

   if(!fun) {

     next();

   }

   fun(req, res, next);

 }

 

热门栏目