2

Say, for instance, I have the following model:

    var advertise = mongoose.Schema({
    username: String,
    text: String,
    locations: Array,
    days: Array,
    phone: Object,
    images: Array,
    age: Number,
    height: String,
    sex: String,
    categories: Array,
    targetAudience: Array,
    prices: Array,
    creator: String,
    hairColor: Object,
    eyeColor: Object,
    breastSize: Object,
    bodyType: Object,
    advertiseType: Object,
    created: {type: Date, default: Date.now},
    is_active: {type: Number, default: 0},
    order_id: String
});

Now I have a value called searchString. Is there a way I can search for all fields with the searchString?

Right now I only know to do this with the $or key. However, this would be impractical.

Like the following:

mongoose.models.advertise.find({$or: [{'username': {'$regex': searchString}}]}, function (err, advertise) {
    res.json(advertise)
})

Note I'm using Node.js

Stibu
  • 15,166
  • 6
  • 57
  • 71
Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364

1 Answers1

0

If you have the ability to create a $text index :

var advertise = mongoose.Schema({
    username: String,
    text: String,
    locations: Array,
    days: Array,
    phone: Object,
    images: Array,
    age: Number,
    height: String,
    sex: String,
    categories: Array,
    targetAudience: Array,
    prices: Array,
    creator: String,
    hairColor: Object,
    eyeColor: Object,
    breastSize: Object,
    bodyType: Object,
    advertiseType: Object,
    created: {type: Date, default: Date.now},
    is_active: {type: Number, default: 0},
    order_id: String
});
advertise.index({ username: 'text', text: 'text', height: 'text', sex: 'text', creator: 'text', order_id: 'text' });

To perform a search :

mongoose.models.advertise.find({ $text : { $search : searchString } }, function (err, advertise) {
    res.json(advertise)
})

I didn't tried for real do not hesitate to correct potential errors.

Julien TASSIN
  • 5,004
  • 1
  • 25
  • 40