0

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.

David
  • 321
  • 10
  • 23
  • Not like this, no. You'd have to be explicit about which collections to query on what fields. – Sergio Tulentsev Jul 27 '20 at 10:57
  • I see. How would I do that? Let's say I want to query (User) `username`, `email` and (Post) `post`. – David Jul 27 '20 at 10:59
  • `db.users.find({"$or": [{"username": /david/}, {"email": /david/}])` and merge its results with results from `db.posts.find({"post": /david/})` – Sergio Tulentsev Jul 27 '20 at 11:08
  • Can we replace that `/david/` with something that the user types in the `search` field? `req.body.search` – David Jul 27 '20 at 11:26
  • Since you are looking for data from both the "joined" collections, you can use the [$lookup](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/index.html) aggregation stage to query the data. – prasad_ Jul 27 '20 at 11:39
  • Does this answer your question? [Search on multiple collections in MongoDB](https://stackoverflow.com/questions/20056903/search-on-multiple-collections-in-mongodb) – turivishal Jul 27 '20 at 12:24

1 Answers1

0

I figured this might work:

const { search } = req.body;

        let searchUser = await User.find({
            username: { $regex: search, $options: "i" },
        }).select("username");

        let searchPost = await Post.find({
            post: { $regex: search, $options: "i" },
        })
            .populate("by")
            .select("post");

        return res.json({
            users: searchUser,
            posts: searchPost,
        });
David
  • 321
  • 10
  • 23