0

I am new to mongoose I don't really find any reference how mongoose populate deals with findMany query having ref

for example I have a categories collection and a products collection as on product can be assigned to many categories that's why they exist in 2 different collections.

Now if I call findMany method on categories collection and also populate with products will mongoose execute per category find products ? or all referenced product ids will be collected and in one query all products will be queried like dataloader do ?

user1592129
  • 461
  • 1
  • 5
  • 16

1 Answers1

2

You should have two schemas, category and product:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const productSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  price: Number,
  // ...
  categories: [{ type: Schema.Types.ObjectId, ref: 'Category' }]
});

module.exports = mongoose.model('Product', productSchema );

const categorySchema = Schema({
  title: String,
  description:String,
  products: [{ type: Schema.Types.ObjectId, ref: 'Product' }]
});

module.exports = mongoose.model('Category', categorySchema );

To find category by id with populated products you could:

app.get('/categories/:id', (req, res) => {

    const categoryId = req.params.id;

    (async () => {
        try {
            const categories = await Categories
                  .find({ _id: categoryId }).populate("products") // you'r populating the property of the schema called products
            res.status(200).json({ results: categories })
        } catch (err) {
            res.status(500).json({ message: "Error ..." })
        }
    })()
});