2014-07-06 132 views
1

我與模式的貓鼬模型中定義爲 -mognoose多列正則表達式搜索

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] 
}); 

和模型定義爲 -

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

現在我想在標題進行搜索,標籤,說明字段從請求對象參數類似

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

現在我該如何做確保在標題或說明中找到該術語的任何結果也包括在內,而不僅僅是兩者中存在的結果。 此外,如何將標籤陣列用於匹配字符串

回答

5

您可以將用戶$或運營商貓鼬與或匹配
$或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); 
}) 

要在陣列匹配字符串搜索的返回結果,你需要使用$ in運營商mongo:

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

+0

根據手冊我需要我想看的數組,但我沒有標籤數組,因爲它在數據庫中。所以我如何使我的查詢搜索數據庫中的一些文本存儲在數據庫中 – DeadMan

+0

$ in操作符如下:'{field:{$ in:[,... ]}} where ,字段是存儲在數據庫中的文檔的實體。手冊清楚地表明,如果** field **是**數組**,$ in操作符將選擇其字段中包含至少包含一個與指定數組中的值匹配的元素的數組的文檔(例如,等)。對於您的用例,字段是** tags **數組,而右側數組只包含一個值,即您要搜索的字符串。 – menirus95

2

使用此查詢,$選項=我會當你將數據插入到TAG陣列跳過小寫/大寫 第一使它小寫和搜索中搜索用小寫字母很容易。

Campusnotes.find({title:{'$regex':searchText,'$option':'i'},description:{'$regex':searchText,'$option':'i'},tags:searchText}, function(err, collection){ 
res.send(collection); 
});