【发布时间】:2015-12-13 06:27:57
【问题描述】:
我正在尝试使用 Node.JS 连接到 MongoDB 数据库(全部托管在 heroku 上,因此使用 MongoLab 插件)来执行文本搜索。我想在我的文档中搜索变量关键字的某些字段(字符串或字符串数组,但我可以将它们更改为所有需要的字符串)。
希望下面的代码可以在“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)) });
}
}
【问题讨论】: