【问题标题】:mongoose findMany query with refs带有参考文献的猫鼬 findMany 查询
【发布时间】:2023-03-10 17:32:01
【问题描述】:

我是 mongoose 的新手,我真的没有找到任何参考资料,mongoose populate 如何处理具有 ref 的 findMany 查询

例如,我有一个 categories 集合和一个 products 集合,因为产品可以分配给许多类别,这就是它们存在于 2 个不同集合中的原因。

现在,如果我在categories 集合上调用findMany 方法,并且还使用populateproducts 调用products,猫鼬会按类别执行查找产品吗?或者将收集所有引用的产品 ID,并在一次查询中查询所有产品,如 dataloader 这样做?

【问题讨论】:

    标签: node.js mongodb mongoose dataloader


    【解决方案1】:

    你应该有两个模式,类别和产品:

    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 );
    

    要通过填充产品的 id 查找类别,您可以:

    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 ..." })
            }
        })()
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-23
    • 2017-12-31
    • 2019-05-20
    • 2013-01-25
    • 2015-08-08
    • 2016-11-02
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多