使MongoDB文本中的表字段可搜索 [英] Make a table's field in MongoDB text searchable

查看:67
本文介绍了使MongoDB文本中的表字段可搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先决条件:

数据库已经使用集合 posts 创建,其架构如下:

Database is created already with the collections posts and it's Schema is as follows:

module.exports = function(mongoose){
var Schema = mongoose.Schema;

var postSchema = new Schema({
   postID:          String,
   title:           String,
   description:     String
});

mongoose.model('post', postSchema, 'posts');
postSchema.index({title: 'text'});

};

节点的路由器通过API处理:

Node's router to handle via an API:

apiRouter.get('/api/searchPosts', function(req, res, next){
    postModel.find(
        { $text : { $search : req.query.text } }, 
        { score : { $meta: "textScore" } }
    )
    .sort({ score : { $meta : 'textScore' } })
    .exec(function(err, posts) {
        if(posts){
            res.json({
                posts       :   posts
            });
        } else {
            res.send('Post does not exist');
        }
    });
});

我要实现的目标:

我想在我的帖子表中创建一个名为 title 文本的可搜索字段.

I want to make a field in my posts table called title text searchable.

我的堆栈:

MongoDB,NodeJS(带有Mongoose),Angular

MongoDB, NodeJS (with Mongoose), Angular

我的方法:

如先决条件中所述,我添加了以下行:

As mentioned in the Prerequisites, I have added the line:

postSchema.index({title: 'text'});

此外,创建集合后,我已经在终端中运行以下命令:

Furthermore, I have run the below command in the terminal once the collections has been created:

db.posts.createIndex({"title":"text"})

问题:

当我从URL访问它时,它最初可以工作,但是几周后,它停止工作(我得到的帖子不存在",无需进行任何更改!).为了使它再次工作,我必须删除集合并重新创建一个集合,然后运行命令:

When I access this from the URL, it works initially but after a few weeks, it stops working (I get 'Post does not exist' without making any changes!). To get it working again, I have to delete the collections and make a fresh one and run the command:

db.posts.createIndex({"title":"text"})

然后它开始工作几周,依此类推.

It then starts working for a few weeks and so on.

我做错了什么?我没有看到这几周发生的事情的趋势.我已经在这个问题上停留了几个星期,所以如果有人可以提供帮助,我们将不胜感激.

What I am doing wrong? I am not seeing a trend about what happens in these few weeks. I have been stuck on this issue for a few weeks so if someone can help, it will be highly appreciated.

谢谢, 沙岩

推荐答案

最后,解决方案如下:

var postSchema = new Schema({
  postID:          String,
  title:           { type: String, text: true },
  description:     String
});

到目前为止,这是成功的窍门.

This did the trick so far.

我将再次检查它,看看是否像每隔几周一样破裂.如果有的话,将对其进行更新.

I will check this again and see if it breaks like it did every few weeks. Will update the post if it does.

感谢Andrei Neagu记录了"err"建议.有时候,显而易见的东西会被错过

Thanks Andrei Neagu for the logging the 'err' suggestion. Sometimes, the obvious ones just get missed

这篇关于使MongoDB文本中的表字段可搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆