使用猫鼬模型添加查询条件

add query conditions using mongoose model

本文关键字:添加 查询 条件 模型      更新时间:2023-09-26

Using Node.js, Mongoose Schema 和 MongoDB,

用户模型架构为

    var mongoose = require('mongoose');
    var Schema   = mongoose.Schema;
    var userSchema = new Schema({
        name:             { type: String, trim: true }
      , address:          { type: String }
      , birth:            { type: Date }
      , tlf:              { type: String }
      , email:            { type: String, lowercase: true }
  });
module.exports = mongoose.model('User', userSchema);

查询用户条件(var cond)、选择(var sel)、选项(var opts)的功能是

 findAllUsers = function (req, res, next) {
    var cond = {
      name : req.query.nm
    };
    var sel = 'name address';
    var opts = { 
        skip: req.query.sk, limit: req.query.lim, sort: req.query.srt
    };
    User.find(cond, sel, opts).lean().exec(function (err, users) {
        if (err) next(err);
        var body = {};
        body.skip = req.query.sk;
        body.limit = req.query.lim;
        body.users= users;
        User.count(cond).exec(function (err, total) {
            if (err) next(err);
             body.total = total;
            res.json(body);
          });
      });
  }

然后,使用正则表达式创建条件的最佳方法是什么,例如,或者... ?

MongoDB中与"like"等效的是regex运算符,将像这样实现:

db.collection.find({ "address": { "$regex": "via" } });

但请记住,与等效的 like "%via%" 语句相同,这确实需要扫描集合中的每个文档(或充其量是索引),以便匹配未"锚定"到字符串开头的字符串。