Search code examples
node.jsmongodbexpressmongoosemongoose-schema

How can I filter arrays in mongodb using mongoose?


I have created database with two collections. Each of these collections connected with relations. Here I want to pass one item _id and check whether it passed to other collection as foreign key. If it's passed, I want to filter all items which consist as _id. How can I do that. Here my mongoose query and screenshot of db. Thank you

route.get("/:id",(req,res)=>{
Vehicles.find({
    categories: [req.params.id]
}, (err, data)=>{
    if(err){
        console.log(err);
    }else{
        console.log(data);
    }
});

MongoDB Screenshot

PS: For an example I want to get all vehicles which have category id "60c58c2dcf82de0780051378" inside categories array.

MongoDB - category collection


Solution

  • Following the mongo document, you can query for all documents where categories is an array that contains the objectId req.params.id as one of its elements.

    Vehicles.find({
      categories: req.params.id,
    }, (err, data) => {
      if (err) {
        console.log(err);
      } else {
        console.log(data);
      }
    });