繁体   English   中英

Mongoose 一对多

[英]Mongoose One to Many

我想在我的类别 model 和产品 model 之间定义一对多的关系。

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)

我的搜索 function

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

function 结果

{
    "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”,

尝试这样做

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM