首页 > 解决方案 > 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

标签: node.jsmongodbexpressmongoosemongoose-schema

解决方案


在 mongo document之后,您可以查询包含 objectId作为其元素之一categories的数组的所有文档。req.params.id

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

推荐阅读