【问题标题】:Mongoose One to Many猫鼬一对多
【发布时间】:2021-06-22 12:17:47
【问题描述】:

我想在我的 Category 模型和 Product 模型之间定义一对多的关系。

product.js(模型)

const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    price:{
        type:Number,
        required:true
    },
    description:{
        type:String,
        required:false
    },
    imageUrl:{
        type:String,
        required:true
    },
    categoryId:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Category'
    }
},
{timestamps:true})  

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

category.js(模型)

const mongoose = require('mongoose');

const categorySchema = mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    products:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Product'
    }]
},
{timestamps:true})  

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

我的搜索功能

exports.findCategoryWithProducts = (req, res, next) => {
    Category.findById(req.params.categoryId)
        .populate('products')
        .then(category => {
            res.status(200).json({ category: category })
        })
        .catch(err => console.log(err))
}

函数结果

{
    "category": {
        "products": [],
        "_id": "6058a54e79e9054d9f9e6821",
        "name": "Pc",
        "createdAt": "2021-03-22T14:10:22.509Z",
        "updatedAt": "2021-03-22T14:10:22.509Z",
        "__v": 0
    }
}

我在这个类别中有 2 个产品,但它给了我空的产品数组。 我错过了什么吗? 版本“猫鼬”:“^5.12.1”,

【问题讨论】:

  • 最好使用聚合函数而不是 findbyId 函数。您可以查看文档:docs.mongodb.com/manual/reference/operator/aggregation/lookup
  • 我建议不要这样做,因为如果您有一个像电话这样的类别并且您有大量电话,那么更新和删除将非常困难并且不直观。但无论如何,请尝试使用 populate({path: "products"}) 让我知道它是否有效。

标签: javascript mongoose one-to-many mongoose-populate odm


【解决方案1】:

我认为 Mongoose ORM 会自动查找与类别和产品的关系。 Mongoose 需要类别上的产品数组来查找关系。所以我将产品数组添加到类别文档中。现在它的工作。 tnx 全部..

【讨论】:

    【解决方案2】:

    尝试这样做

    exports.findCategoryWithProducts = (req, res, next) => {
      Category.findById(req.params.categoryId).populate('products').execPopulate()
        .then(category => {
          res.status(200).json({
            category: category
          })
        }).catch(err => console.log(err))
    }
    

    【讨论】:

    • { "message": "Category.findById(...).populate(...).execPopulate 不是函数" }
    • 当然这是我以前使用的功能检查 [link]mongoosejs.com/docs/api/…
    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 2018-01-22
    • 2018-08-23
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    相关资源
    最近更新 更多