I used to have a Comment
schema, where I held author
, comment
and commentID
fields, essentially duplicating author's name for every comment that belonged to him. So I refactored it as following. Now I have an Author
model with an array of his comments, it does feel better but I've lost the ability to query commentBody
via fulltext search. Before I would just query Comment
model with the term and it returned me every comment that met the criteria.
const authorSchema = new mongoose.Schema({
name: { type: String, unique: true, index: true },
comments: [{
commentID: { type: String, unique: true },
commentBody: { type: String, index: 'text' },
created_at: { type: Date, default: Date.now }
}],
...
// other unrelated fields
});
But now when I'm trying to query Author
model directly like this:
Author.find({ $text: { $search: `${req.params.term}` } })
.select('name comments')
.exec((error, result) => {
res.json(result);
});
it righteously so returns me every match of Author
if at least one of his comments meets searching criteria. I've spent couple of hours reading Mongoose and MongoDB's docs, but I still can't write a proper query that will return only matched comments within the comments array, i.e. for term lorem
I want the follow response:
{
name: "Jane",
comments: [
{
commentBody: "Lorem dolor",
commentID: "42",
},
{
commentBody: "Lorem lipsum.",
commentID: "43",
},
]
},
{
name: "Doe",
comments: [
{
commentBody: "Dolor lorem",
commentID: "44",
},
{
commentBody: "Lipsum lorem.",
commentID: "45",
},
]
}