简体   繁体   中英

Creating Search/filter in express mongo react

im trying to build a filter menu to filter the incoming data from mongodb. im using the.find(); function to limit the incoming data.

usage like this Post.find({boatType: "Cruiser"})

So here is what ive got so far. I transfer the data that i need to filter via query

const res = await axios.get(`/api/posts/`,
            {
                params: {
                    hull: "Catamaran",
                    boatType: "Cruiser",
                    seller: "Private",
                    etc..
                }
            });

express Backend

const posts = await Post.find({exampleField: "exampleFilter"});

and this is where im stuck. After i pass the queries to the node backend, i have no idea how to get the.find() function to work across multiple fields. and even more confusing for me is that these queries will be dynamic. Sometimes the "hull" query will not be there, or it might be that "seller" is not there, etc etc. Is there a better way to do what im doing? Should i be using $Regex or $in... im lost and the documentation is doing me no favors.

all help is appreciated.

you should just pass your query object to Post.find() , like this:

app.get('/api/posts' , (req, res) => {
    // you can access the query from req.query
    const posts = await Post.find(req.query);
})

You can check here and here for more details.

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