Home > database >  How to return all documents that have a field that contains a given string
How to return all documents that have a field that contains a given string

Time:06-01

I have a question, I'm creating a react app, using Node and MongoDB as back-end, and I'm trying to get all the documents from a collection, that have a field that contains a given string. This is how I tried it, when I leave the params empty, it does return all the movies, but when I'm typing something after the "/" it gives me an error In my case I'm trying to get all the movies, whose title contains some letters, to implement a search component

router.get("/:query", async (req, res) => {
    let listTemp = [];
    listTemp = await Movie.find({$contains:{"title": {$regex : req.params.query}}});
    try {
        ids = []
        listTemp.forEach(elem => {
          ids.push(elem._id);
        })
        res.status(200).json(ids);
    } catch (err) {
        res.status(500).json(err);
    }
}
);

CodePudding user response:

You can try this

Movie.find({title: { $regex: '.*' req.params.query '.*' } });

  • Related