2017-02-20 58 views
2

使用下面的代碼,我得到的錯誤TypeError: db.collection.createIndex is not a function,我要用來執行從該網站的搜索功能:https://docs.mongodb.com/manual/text-search/類型錯誤:db.collection.createIndex是不是在搜索功能的功能明確項目

也許有另一種方法來搜索MongoDB?

+0

通過上述工作流程你注意到你總是創建每次建立連接時的指數?另外,['createIndex'](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex)是異步的。 – chridam

回答

0

您可能想要在創建索引之前檢查索引是否存在。使用indexExists功能檢查:

mongodb.MongoClient.connect(url, function(err, db) { 
    var collection = db.collection('Modules'); 
    collection.indexExists('Name_text_Code_text').then(function(indexExists){ 
     if(!indexExists) 
      collection.createIndex({ Name: 'text', Code: 'text' }); 
    }).then(function(result){ 
     collection.find({ 
      $test: { 
       $search: "Bob", 
       $caseSensitive: false 
      } 
     }).toArray(); 
    }).then(function(results) { 
     db.close(); 
     res.json(results); 
     console.log("SEARCH IS WORKING"); 
    }); 
});