Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 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 Reply

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...