Prerequisites:
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'});
};
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');
}
});
});
What I am trying to achieve:
I want to make a field in my posts table called title text searchable.
My stack:
MongoDB, NodeJS (with Mongoose), Angular
My approach:
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"})
The problem:
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.
Thanks, Shayan
In the end, the solution was as below:
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.
Thanks Andrei Neagu for the logging the 'err' suggestion. Sometimes, the obvious ones just get missed