TypeError:db.collection.createIndex不是快速项目的搜索功能中的函数

时间:2017-02-20 05:30:50

标签: node.js mongodb express

使用下面的代码,我收到错误TypeError: db.collection.createIndex is not a function,我想用它来实现此网站的搜索功能:https://docs.mongodb.com/manual/text-search/

也许有另一种方法可以搜索MongoDB?

 app.post('/search', function(req, res) {
        var results = [];
        mongodb.MongoClient.connect(url, function(err, db) {
            db.collection.createIndex( { Name: "text", Code: "text" } );
            var searcher = db.collection('Modules').find({
                $test: {
                    $search: "Bob",
                    $caseSensitive: false
                }
            });
            searcher.forEach(function(doc, err) {
                //assert.equal(null, err);
                results.push(doc);
            }, function() {
                db.close();
                res.json(results);
                console.log("SEARCH IS WORKING")
            });
        });
    });

1 个答案:

答案 0 :(得分:1)

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