gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:41:29 25 4
gpt4 key购买 nike

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

最佳答案

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

关于node.js - TypeError : db. collection.createIndex 不是快速项目搜索功能中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42337131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com