首页 文章

使用mongoose模型添加查询条件

提问于
浏览
0

使用Node.js,Mongoose Schema和MongoDB,

用户模型Schema是

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),select(var sel),options(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);
          });
      });
  }

那么,用regexp创建条件的最佳方法是什么,比如,还是......?

1 回答

  • 0

    相当于MongoDB中的"like"是regex运算符,可以像这样实现:

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

    但请记住,这与等效的 like "%via%" 语句相同,这个 does 需要扫描集合中的每个文档(或最好的索引),以便将不是"anchored"的字符串与字符串的 start 匹配 .

相关问题