skip to Main Content

Messing around with aggregations in MongoDB in a Node / Express app with Mongoose. Here’s the route:

router.get("/search", async (req, res) => {
    let movies;
    if(req.query.search){
        escapeRegex(req.query.search);
        const regex = new RegExp(escapeRegex(req.query.search), 'gi');
    
        movies = await Movie.aggregate(
            [
                { '$match': {'title': regex} },
                { '$limit': 5 }
            ], (err, result) => {
                if (err) {
                    console.log(err)
                } else {
                    console.log(result)
                }
            }
    );

    console.log("Result:", movies);
    res.render("atlas/search", {movies: returnedMovies});

} else {
    Movie.find({}).sort('title').limit(10).exec((err, allMovies) => {
        if(err){
            console.log(err);
        } else {
            res.render("atlas/search",{movies: allMovies});
        }
    });
  }
});

Essentially what I’m doing here is taking in user input from a search bar, then running that input through an aggregation; however, I’m unable to get any results (hits my 404 not found page) and nothing is returned to the console through any of my console.log attempts. The else route, where if no search is present return the first 10 movies, works perfectly fine.

What am I missing here?

2

Answers


  1. replace this code

    escapeRegex(req.query.search);
    const regex = new RegExp(escapeRegex(req.query.search), 'gi');
    

    to

    const regex = new RegExp(req.query.search, 'i');
    

    this might help out

    Login or Signup to reply.
  2. To do a regex-based search, you need to use the operator $regex in your $match stage. Like this:

    { '$match': {'title': { $regex: regex } } }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search