简体   繁体   中英

Search and query whole database in MongoDB

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 .

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,
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM