I'm currently developing a search feature that allows users to input a specific query and retrieve all messages containing that query.
The search process involves sending a query to the database based on the current message context when the user initiates the search.
Here is an example of the data structure returned by Messages.find()
:
const input = [
{
"_id": "1",
"firstName": "John",
"last_name": "Doe",
"message_id": "12345",
"messages": [
{
"time": "Thu Aug 05 2021 19:31:15 GMT-0700 (Pacific Daylight Time)",
"text": "hey there"
},
...
],
"__v": 0
},
...
]
In this scenario, I am looking to filter out only those items that contain the keyword "hey".
const expected = [
{
"_id": "1",
"firstName": "John",
"last_name": "Doe",
"message_id": "12345",
"messages": [
{
"time": "Thu Aug 05 2021 19:31:15 GMT-0700 (Pacific Daylight Time)",
"text": "hey there"
},
...
],
"__v": 0
},
...
]
The method I am currently using to achieve this involves iterating through the messages and filtering them based on the presence of the keyword "hey."
Message.find({message_id})
.then((messages) => {
let filtered = messages.map(item => {
let filteredMessages = item.messages.filter(message => {
return message.text.toLowerCase().match(new RegExp("\\b" + "hey" + "\\b")) != null;
});
return {...item, messages: filteredMessages};
}).filter(empty => empty.messages.length > 0);