我試圖使用Node.JS
連接到MongoDB數據庫(所有託管在heroku
,因此使用MongoLab
插件)來執行文本搜索。我想爲可變關鍵字搜索我的文檔的某些字段(字符串或字符串數組,但是我可以將它們更改爲所有需要的字符串)。mongoDB - 使用node.js在多個字段中搜索文本
下面的代碼希望做的是搜索關鍵字變量的'title'字段或'ingredients'字段,然後返回這些結果。 我懷疑ensureIndex
行(嘗試ensureIndex
和createIndex
),因爲刪除它們並不會改變程序的功能。
任何幫助,將不勝感激!
app.get('/searchtitle', function(request, response) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "X-Requested-With");
response.set('Content-Type', 'application/json');
var type = request.query.type;
var keyword = request.query.keyword;
if (type == 'title') {
db.collection('Test_Recipes').ensureIndex({ title: "text" });
db.collection('Test_Recipes').find({
$text: {$search: keyword }
}).toArray(function(err, results){
response.send(JSON.stringify(results)) });
}
else {
console.log("in else case: type is "
+ type + " and keyword is " +keyword);
db.collection('Test_Recipes').ensureIndex({ingredients :"text"});
db.collection('Test_Recipes').find({
ingredients: {$elemMatch: keyword } })
.toArray(function(err, results){
response.send(JSON.stringify(results)) });
}
}