$in Operator in MongoDB usecases
Abheetha Pradhan
2 min read
Show a feed of posts made only by users you are following like X’s “Following” section
const followingIds = ['user1', 'user2', 'user3'];
//Get posts from your following list in the last 24 hours and sort them in descending order
const feedPosts = await Post.find({
author: { $in: followingIds },
createdAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) }
}).sort({ createdAt: -1 });
Select multiple filters of the same category
Say you have a state that stores multiple filters of the same category and you want to send this in your REST API
In Express, when multiple query parameters have the same name (e.g., ?filter=shirt&filter=pants
), the framework handles them by parsing the repeated parameters into an array. This means if a URL includes the query string ?filter=shirt&filter=pants
, Express will parse req.query.filter
as an array: ['shirt', 'pants']
However, If you send only one filter (e.g., ?filter=shirt
), Express will parse req.query.filter
as a string instead of an array.
http://127.0.0.1:4000/api?filter=red&filter=black&filter=grey
//Frontend
const url = "http://127.0.0.1:4000/api?brand=nike"
const queryString = selectedFilters.map(filter => `filter=${encodeURIComponent(filter)}`).join('&');
fetch(`${url}${queryString}`)
.then(res => res.json())
.then(data => {
setData(data);
}
//Backend
const getData = async (req, res) => {
// Extract the filter parameter from the query string
let { filter=[], brand } = req.query;
if(typeof filter === "string"){
filter = [filter]
}
let query = {brand: brand};
if (filter && filter.length > 0) {
query = { ...query, type: { $in: filter }};
}
const clothes = await clothesModel.find(query).exec();
}
0
Subscribe to my newsletter
Read articles from Abheetha Pradhan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by