erichardson30
erichardson30

Reputation: 5054

Mongodb Mongoose complex query for search

I am trying to implement a dynamic search bar that shows suggestions based on what the user types in. Example you start typing "j" and you see options such as "Java, JavaScript, JQuery" ... then you type "ja" and only see "Java, JavaScript".

My schema looks like this :

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var QuestionSchema = new Schema({
    text : String,
    answers : Array,
    tech : String,
    tags : [String],
    level : String,
    createdAt : Date
});

// Return the model
module.exports = mongoose.model('Questions', QuestionSchema);

And I need the search to look for matches in 'text', 'tech', 'tags', and 'level'.

Upvotes: 0

Views: 799

Answers (1)

Yerken
Yerken

Reputation: 1942

There you go

let query = [
        { 'text': { $regex: new RegExp(keyword, "i") } },
        { 'tech': { $regex: new RegExp(keyword, "i") } },
        { 'tags': { $regex: new RegExp(keyword, "i") } },
        { 'level': { $regex: new RegExp(keyword, "i") } }
    ]

    Question.find({ $or: query }, function(err, results){
...
    });

Upvotes: 3

Related Questions