Search code examples
node.jsmongoose

How to filter documents based on array value in mongoose


I have a mongoDB database with a value of tagTable which takes an array. In this tag table there are 3 categories: hunting, fishing, and camping. I tried to filter using tagTable:hunting like in the code below, but that just sees if the tagTable value is a string of "hunting", not checking to see if it has a string of hunting inside of it. How can I achieve this?

router.get("/home", (req, res)=>{

  Blog.find({tagTable: "hunting"}).then(huntingBlogs=>{
    console.log(huntingBlogs);
  })

  Blog.find({}).then(arrayOfLatestBlogs=>{
    res.render("Home" , {
                          metaDetails: {title: "Coach Outdoor", description: descriptionParameter},
                          blogDetails: {latestBlogs: arrayOfLatestBlogs.slice(0,9)}
                        });
  })

})

Solution

  • What you are probably looking for is the $in operator. You can find the documentation for the $in here.

    For specific use case to mongoose, please refer the mongoose documentation here.

    In your case, the solution would be,

    // Notice the brackets around "hunting"
    Blog.find({tagTable: ["hunting"]}).then(huntingBlogs=>{
        console.log(huntingBlogs);
    })
    

    Thanks