I would like to implement a search field in my React app. In MongoDB I have 1 database and 2 collections inside it (users, posts).
Is it possible to query both collections based on what is written inside the search bar?
exports.search = async (req, res) => {
const { search } = req.body;
try {
let search = await User.aggregate([{ $match: { search } }]);
return res.json(search)
} catch (err) {
console.error(err.message);
res.status(500).send("Server error.");
}
};
Obviously this one doesn't work because db
is not specified, but I want that to be the database.
I just want to return whatever the user types in the search field.
User looks like this:
{
"_id": "12131231231231213",
"username": "David",
"email": "david@email.com",
"friends": []
}
Post looks like this:
{
"_id": "5436435345354354",
"post": "a random post",
"by": "david@email.com",
"likes": 3
}
So if I typed 'David' in the search field then it should return that post and user too. If I just typed 'random' then only that post.
Let's say I want to query (User) username
, email
and (Post) post
.