Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a mongoose model with schema defined as -

var campusNotesSchema = mongoose.Schema({
    noteId:{type:String, unique:true, default: uuid.v4()},
    title: {type:String, required:'{PATH} is required!'},
    uploader:{type:String,required:'{PATH} is required!'},
    department:{type:String},
    college:{type:String},
    author:{type:String,required:'{PATH} is required!'},
    actualFileName: [String],
    storedFileName: [String],
    subject: {type:String},
    description: {type:String},
    details: {type:String},
    date: {type:Date, default: Date},
    tags: [String]
});

and the model defined as -

var Campusnotes = mongoose.model('Campusnotes', campusNotesSchema);

Now I want to search in the title, tags, description field from the request objects parameters something like

if(req.query.searchText){        
    Campusnotes.find({title:new RegExp(searchText,'i'),description:new RegExp(searchText,'i')}).exec(function(err, collection) {
        res.send(collection);
    })
}

Now how do i make sure that any results in which the term is found in either title or description is also included and not only the ones which are there in both of them. Also, how do i search in the tags array for the matching strings

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
639 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can user $or operator in mongoose to return results with either of matches
$or http://docs.mongodb.org/manual/reference/operator/query/or/

Campusnotes.find({'$or':[{title:new RegExp(searchText,'i')},{description:new RegExp(searchText,'i')}]}).exec(function(err, collection) {
    res.send(collection);
})

To search in array for matching strings, you need to use $in operator of mongo:

$in : http://docs.mongodb.org/manual/reference/operator/query/in/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...