使用mongoose模型添加查询条件

时间:2014-04-05 11:16:02

标签: javascript regex node.js mongodb mongoose

使用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 :(得分:0)

MongoDB中“like”的等价物是regex运算符,可以这样实现:

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

请注意,与同等like "%via%"语句相同,此 需要扫描集合中的每个文档(或者最好index)以便将非"anchored"的字符串与字符串的 start 相匹配。