2017-03-28 185 views
1

說所有的領域,例如,我有以下型號:

var advertise = mongoose.Schema({ 
    username: String, 
    text: String, 
    locations: Array, 
    days: Array, 
    phone: Object, 
    images: Array, 
    age: Number, 
    height: String, 
    sex: String, 
    categories: Array, 
    targetAudience: Array, 
    prices: Array, 
    creator: String, 
    hairColor: Object, 
    eyeColor: Object, 
    breastSize: Object, 
    bodyType: Object, 
    advertiseType: Object, 
    created: {type: Date, default: Date.now}, 
    is_active: {type: Number, default: 0}, 
    order_id: String 
}); 

現在我有一個名爲searchString值。有沒有一種方法可以搜索searchString的所有字段?

現在我只知道用$or這個鍵來做到這一點。但是,這是不切實際的。

類似如下:

mongoose.models.advertise.find({$or: [{'username': {'$regex': searchString}}]}, function (err, advertise) { 
    res.json(advertise) 
}) 

注意我使用Node.js

+0

你有沒有可能用貓鼬創建文本索引?我認爲這將是最方便的方式。 –

回答

1

如果你需要創建一個$text index的能力:

var advertise = mongoose.Schema({ 
    username: String, 
    text: String, 
    locations: Array, 
    days: Array, 
    phone: Object, 
    images: Array, 
    age: Number, 
    height: String, 
    sex: String, 
    categories: Array, 
    targetAudience: Array, 
    prices: Array, 
    creator: String, 
    hairColor: Object, 
    eyeColor: Object, 
    breastSize: Object, 
    bodyType: Object, 
    advertiseType: Object, 
    created: {type: Date, default: Date.now}, 
    is_active: {type: Number, default: 0}, 
    order_id: String 
}); 
advertise.index({ username: 'text', text: 'text', height: 'text', sex: 'text', creator: 'text', order_id: 'text' }); 

爲了執行搜索:

mongoose.models.advertise.find({ $text : { $search : searchString } }, function (err, advertise) { 
    res.json(advertise) 
}) 

我沒有試過真的不要猶豫糾正潛在的錯誤。