简体   繁体   中英

Query MongoDb for multiple fields with $regex

I'm following the Angular Meteor tutorials, and it has the following code:

import { Meteor } from 'meteor/meteor';
import { Counts } from 'meteor/tmeasday:publish-counts';

import { Parties } from './collection';

if (Meteor.isServer) {
  Meteor.publish('parties', function(options, searchString) {
    const selector = {
      $or: [{
        // the public parties
        $and: [{
          public: true
        }, {
          public: {
            $exists: true
          }
        }]
      }, {
        // when logged in user is the owner
        $and: [{
          owner: this.userId
        }, {
          owner: {
            $exists: true
          }
        }]
      }]
    };

    if (typeof searchString === 'string' && searchString.length) {
      selector.name = {
        $regex: `.*${searchString}.*`,
        $options : 'i'
      };
    }

    Counts.publish(this, 'numberOfParties', Parties.find(selector), {
      noReady: true
    });

    return Parties.find(selector, options);
  });
}

I am trying to modify the selector.name to include the description field as well. I've checked adding selector.description, however that does nothing. Is it possible to modify the selector to include searching of multiple fields while matching the regex with either field of the document?

By "either" you probably mean an $or: - if you just add description to the object then you'll end up with an $and:

Before you get to the name and description criteria, your selector is going to be:

let selector =
  { $or:
    [
      { $and: [ { public: true }, { public: { $exists: true } } ] },
      { $and: [ { owner: this.userId }, { owner: { $exists: true } }] }
    ]
  };

(note the let instead of const )

To this you want to $and: append a second $or:

if (typeof searchString === 'string' && searchString.length) {
  selector = { $and:
    [ 
      selector,
      { $or:
        [
          { name: { $regex: `.*${searchString}.*`, $options : 'i' }},
          { description: { $regex: `.*${searchString}.*`, $options : 'i' }},
        ]
      }
    ]
  };
}

At the end, you should have an object that looks like:

{ $and:
  [ 
    { $or: [ public criteria, owner criteria ] },
    { $or: [ name regex, description regex ] }
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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