Ayat
Ayat

Reputation: 1

How can i Join in mongodb and covert this SQL code to mongoose

select*
from AvailableProperty as a JOIN Branch as b 
where a.branchId=b._id

I tried this but it's not working properly.

 let data = await AvailableProperty.find({ Type_property: "Sell" })
    .populate({
      path: "branchId",
      match: { _id: req.user.id},
      select: "name _id adressNumber1 adressNumber2 status",
    })

Upvotes: 0

Views: 65

Answers (2)

CS Student
CS Student

Reputation: 146

Here is how to use populate() to get the same result as the SQL query you provided in your question:

const query = AvailableProperty.find().populate('branchId'); 

// Execute the query and populate the results 
query.exec((err, properties) => {
  if (err) {
    // handle error
  } 
  else {
    // you can access joined documents here 
  } 
});

Notice that branchId references the _id field in the Branch model.

Upvotes: 0

Lars Vonk
Lars Vonk

Reputation: 738

I think you are missing the reference in your Schema. If you add the reference information from what you are passing to the populate function in the Schema and then populate is suspect it would work!

For reference: https://mongoosejs.com/docs/populate.html

Upvotes: 1

Related Questions