简体   繁体   English

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

[英]add query conditions using mongoose model

using Node.js, Mongoose Schema and MongoDB, 使用Node.js,Mongoose Schema和MongoDB,

the user model Schema is 用户模型架构为

    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);

and the function to query users with conditions (var cond), select (var sel), options (var opts) is 和查询条件(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);
          });
      });
  }

and then, what is the best way to create a conditions with regexp, like, or... ? 然后,使用regexp(如...)创建条件的最佳方法是什么?

The equivalent to "like" in MongoDB is the regex operator and would be implemented like this: 在MongoDB中,相当于“ like”的是regex运算符,可以这样实现:

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

Keep in mind though, that just the same as the equivalent like "%via%" statement, this does need to scan every document in the collection (or at best index) in order to match the string that is not "anchored" to the start of the string. 但是请记住, like "%via%"语句等价物相同,这确实需要扫描集合中的每个文档(或最好是索引),以便将未“锚定”的字符串与字符串的开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM