类型错误:db.collection.createIndex是不是在搜索功能的功能明确项目

问题描述:

使用下面的代码,我得到的错误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

您可能想要在创建索引之前检查索引是否存在。使用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"); 
    }); 
});