【问题标题】:text index required for $text query in the MongoDB with Express使用 Express 在 MongoDB 中进行 $text 查询所需的文本索引
【发布时间】:2021-03-22 15:40:57
【问题描述】:

我建立了一个连接到本地 MongoDB 的 Express 后端

当我创建帖子以查找特定术语时,它会返回这样的错误

MongoError: text index required for $text query

我该如何解决这个错误?

这是我的快递代码

app.post("/api/search",(req,res)=> {

    const term = req.body.searchTerm;

    console.log(term); // Here I can check the request coming well

    MongoClient.connect(url,(err,db)=> {
        if(err) throw err;

        const dbo = db.db("Exercise");
        dbo.collection("exercise")
            .find({$text:{$search:term}})
            .toArray((error, result) => {
                if (error) {
                  console.log(error);
                  return;
                } else {
                    console.log("Success");
                  res.send(result);
                }
              });
    });
});

Thank you in advance!

【问题讨论】:

    标签: mongodb express axios


    【解决方案1】:

    解决问题的方法很简单。您可以在要在集合中搜索的字段上创建一个“文本”,如下所示:

    db.reviews.createIndex( { comments: "text" } ) 
    

    注意:assumes "comments" is the field as seen in the docs

    但是,为了获得最佳结果,您可能需要创建一个dynamic default Search index in MongoDB Atlas。它是免费且容易的。因为它是动态默认的,所以不需要做任何配置。如果您提供搜索体验,结果和性能可能会更好。

    我希望这些信息对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 2020-05-12
      • 2019-08-16
      • 2015-09-15
      • 2019-06-03
      • 2015-02-20
      • 1970-01-01
      • 2015-09-18
      相关资源
      最近更新 更多