user2578666
user2578666

Reputation: 1143

Search for an array match in MongoDB

I have a schema like this in Mongo DB:

MAIN:

    var mySchema= new mongoose.Schema({
    username: { type: String, unique: true },
    custom_schema: [mongoose.modelSchemas.Custom]
    });
app.db.model('Main', mySchema);

My Custom schema looks like this:

    var custom_schema = new mongoose.Schema({
        my_string:{type:String, default: '' },
        somefield: {
         //
        }
      });
app.db.model('Custom', custom_Schema);

I need to retrive all records from the data base whose custom_schema contains a specific string in the string my_string.

I am doing this right now:

var filters = {};
  filters.somefield=new RegExp('^.*?'+city+'.*$', 'i');

  req.app.db.models.Main.pagedFind({
    filters: filters,
    keys: 'mykeys',
    limit: 1000,
    page: 1,
    sort: '_by something'
  }, function(err, results) {
    if (err) {
      return next(err);
    }
  });

How do I add a filter to search for a particular string in the array of custom_Schema?

Upvotes: 0

Views: 94

Answers (1)

monkeyinsight
monkeyinsight

Reputation: 4859

To search inside object in mongodb, you need to use same directives as you do in regular Object object.var, so your filters should look like filters['custom_schema.somefield'] = ...

Upvotes: 1

Related Questions