Nodejs下mongodb的模糊查询、灵活查询(小例子一枚)

Nodejs下mongodb的模糊查询、灵活查询(小例子一枚)

查询函数调用时的工作:

//index.js
exports.problemset = function(req, res) {
  var str = req.query.search, page = parseInt(req.query.page);
  var q = {};    //定义空的查询对象
  if (str) {    //如果有搜索请求就增加查询条件
    //用正则表达式得到的pattern对title属性进行模糊查询
    //这里是搜集合里title属性包含str串的所有结果
    var pattern = new RegExp("^.*"+str+".*$");
    q.title = pattern;
  }
  if (!page) page = 1;
  var order = req.query.order;
  var sq = {}, Str, A = 'problemID', B = 'asc';
  if (order) {    //是否有排序请求
    Str = order.split('_');
    A = Str[0]; B = Str[1];
    sq[A] = B;    //关联数组增加查询条件,更加灵活,因为A是变量
  } else {
    sq.problemID = 1;    //默认排序查询条件
  }
  Problem.get (q, sq, page, function(err, problems, pn) {
    if (err) {
      req.flash('error', err);
      return res.redirect('/');
    }
    //to do ...
  });
};

查询函数的定义:

//problem.js
......//前面省略,这里用的是mongoose操作
Problem.get = function get(q, sq, n, callback) {
  problems.find(q).sort(sq).find(function(err, docs){
    if (err) {
      return callback('Problems matched failed', null, 1);
    }
    return callback(err, docs.slice((n-1)*20,n*20), docs.length);
  });
};

6 回复

Node.js 下 MongoDB 的模糊查询、灵活查询(小例子一枚)

查询函数调用时的工作

首先,我们来看一下如何在 Express 中处理模糊查询和灵活查询。假设我们有一个 /problemset 路由,用户可以通过查询参数 searchpage 来进行搜索和分页。

// index.js
const express = require('express');
const router = express.Router();
const Problem = require('./models/problem'); // 假设你已经定义了问题模型

router.get('/problemset', function(req, res) {
  const str = req.query.search;
  const page = parseInt(req.query.page) || 1;
  let q = {}; // 定义空的查询对象

  if (str) {
    // 使用正则表达式进行模糊查询
    const pattern = new RegExp(`.*${str}.*`, 'i'); // 'i' 表示不区分大小写
    q.title = { $regex: pattern };
  }

  const order = req.query.order;
  let sortObj = {};
  
  if (order) {
    const [field, direction] = order.split('_');
    sortObj[field] = direction === 'asc' ? 1 : -1;
  } else {
    sortObj.problemID = 1; // 默认按 problemID 升序排序
  }

  Problem.get(q, sortObj, page, function(err, problems, total) {
    if (err) {
      req.flash('error', err);
      return res.redirect('/');
    }
    res.render('problemset', { problems, page, total });
  });
});

module.exports = router;

查询函数的定义

接下来,我们定义一个 get 方法来处理查询逻辑。这里使用 Mongoose 操作 MongoDB 数据库。

// problem.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const problemSchema = new Schema({
  title: String,
  problemID: Number,
  content: String
});

const Problem = mongoose.model('Problem', problemSchema);

Problem.get = function(q, sort, page, callback) {
  const limit = 20; // 每页显示的条目数
  const skip = (page - 1) * limit;

  this.find(q)
    .sort(sort)
    .skip(skip)
    .limit(limit)
    .exec(function(err, docs) {
      if (err) {
        return callback('Problems matched failed', null, 1);
      }
      this.countDocuments(q, function(err, total) {
        if (err) {
          return callback('Count failed', null, 1);
        }
        return callback(null, docs, total);
      });
    }.bind(this));
};

module.exports = Problem;

解释

  1. 模糊查询:通过正则表达式 RegExp 进行模糊匹配,例如 new RegExp(.${str}., 'i')
  2. 灵活排序:通过动态生成排序对象 sortObj,支持多种字段和排序方向。
  3. 分页:通过 skiplimit 实现分页功能,每页显示 20 条记录。
  4. 错误处理:在查询过程中处理可能出现的错误,并通过回调函数返回结果。

以上代码展示了如何在 Node.js 中使用 Mongoose 对 MongoDB 进行模糊查询和灵活排序。希望这个示例对你有所帮助!


谢谢你,DolphinBoy~

错误的时候记录下日志吧

非常棒,这样的话,查询就非常灵活了。。。

以下是如何在 Node.js 下使用 MongoDB 进行模糊查询和灵活查询的小例子。我们将使用 Mongoose 来简化 MongoDB 的操作。

模糊查询

假设我们有一个 Problem 模型,并且希望根据题目标题进行模糊查询:

// problem.js
const mongoose = require('mongoose');

const ProblemSchema = new mongoose.Schema({
  title: String,
  problemID: Number,
});

const Problem = mongoose.model('Problem', ProblemSchema);

module.exports = Problem;

在控制器中执行模糊查询:

// index.js
const Problem = require('./problem');

exports.problemset = async (req, res) => {
  const str = req.query.search || '';
  const page = parseInt(req.query.page) || 1;
  const order = req.query.order || 'problemID_asc';

  let query = {};
  if (str) {
    const pattern = new RegExp(str, 'i'); // 忽略大小写
    query.title = { $regex: pattern };
  }

  let sort = {};
  const [field, direction] = order.split('_');
  sort[field] = direction === 'asc' ? 1 : -1;

  try {
    const problems = await Problem.find(query)
      .sort(sort)
      .skip((page - 1) * 20)
      .limit(20);

    const total = await Problem.countDocuments(query);
    res.render('problems', { problems, currentPage: page, totalPages: Math.ceil(total / 20) });
  } catch (err) {
    req.flash('error', err.message);
    res.redirect('/');
  }
};

灵活查询

为了实现更灵活的查询,我们可以使用 Mongoose 的查询构建器来组合多个查询条件:

// index.js
exports.problemset = async (req, res) => {
  const searchParams = req.query;
  const { search, page = 1, order = 'problemID_asc' } = searchParams;

  const query = {};

  if (search) {
    const pattern = new RegExp(search, 'i');
    query.title = { $regex: pattern };
  }

  let sort = {};
  const [field, direction] = order.split('_');
  sort[field] = direction === 'asc' ? 1 : -1;

  try {
    const problems = await Problem.find(query)
      .sort(sort)
      .skip((page - 1) * 20)
      .limit(20);

    const total = await Problem.countDocuments(query);
    res.render('problems', { problems, currentPage: page, totalPages: Math.ceil(total / 20) });
  } catch (err) {
    req.flash('error', err.message);
    res.redirect('/');
  }
};

通过这种方式,你可以轻松地扩展查询条件,以适应更复杂的搜索需求。

回到顶部