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

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

regex - mognoose searching with regular expression in multiple columns

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

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

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...