0

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

3
  • Can you share a sample JSON data from both the collections? Commented Jun 13, 2021 at 5:39
  • @hhharsha36 I updated question with new ss. can you check it please? Commented Jun 13, 2021 at 5:41
  • Please share sample input in JSON instead of screenshot and expected output. Its difficult to interpret by screenshot reference. Commented Jun 13, 2021 at 6:13

1 Answer 1

1

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);
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.