I have table containing Title
, Sub-Title
and Count
. sub-title
is the child of title
.So, in the collection of title
, objectId
of sub-title
is saved.
Below is the screenshot of the table.
If I try to search a particular title say Fruits I get the table where the title is Fruits.
Now suppose say I try searching with Sub-Title and search apple I do not get result containing only apple or any row where apple is present. Instead, I get all the data of that title as well along with the searched data.
Below is the code:
titleSubTitle.js
class titleSubTitle extends Component {
constructor() {
super();
this.state = { title: "", subtitle: "", filter: {} };
}
fetch = () => {
let subtitle = [];
let subtitleIds = [];
this.props.data.map((title) => {
subtitle.push(
title.children.find((subtitle) =>
subtitle.name.includes(this.state.subtitle)
)
);
});
subtitle.forEach((element) => {
if (element && element._id) {
subtitleIds.push(element._id);
}
});
let data = {
title: this.state.title,
subtitle: subtitleIds,
};
this.filteringData(data);
};
filteringData = async (data) => {
await this.setState({ filter: data });
this.getData();
};
getData = async () => {
let data = {
data: {
title:
this.state.filter && this.state.filter.title
? this.state.filter.title
: null,
subtitle:
this.state.filter && this.state.filter.subtitle
? this.state.filter.subtitle
: null,
},
};
await this.props.getSequence(data);
};
handleFilterChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
}
render() {
return (
<TextField
label="Title"
value={this.state.title}
onChange={this.handleFilterChange}
/>
<TextField
label="Sub-Title"
value={this.state.subtitle}
onChange={this.handleFilterChange}
/>
<Button type="submit" onClick={this.fetch}>
Search
</Button>
</>
);
}
}
Below is the back-end code:
getSequence: async function (req, res) {
try {
let query = {
type: 'Title'
};
if (req.query.title) {
query.titlename = new RegExp(req.query.title, 'i')
}
if (req.query.subtitle) {
query.subtitlename = { $in: req.query.subtitle }
}
let sequence= await titlesubtitle.find(query);
let dataList = await titlesubtitle.find(query);
let count = await titlesubtitle.find(query).countDocuments();
let response = {
data: sequence,
totalCount: count,
dataList : dataList
}
return res.send(response);
} catch (error){
return res.send('Error');
}
}
So, I'll explain what I want the result as again.
Upon search of sub-title say apple I want the table to show all the records where only apple is present. No extra records to be shown of other sub-title.
Upon search of title as Fruits and sub-title as pear, I want only 1 record which is obvious as the result.
If I search for a record that is not present then the table should be empty. This should apply to all the combinations.
I cannot figure where I am going wrong. Can anyone help me out with this please.
See Question&Answers more detail:
os