简体   繁体   中英

Mongoose One to Many

I want to define a one-to-many relationship between my Category model and Product model.

product.js (Model)

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 (Model)

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)

My search 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 result

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

I have 2 products in this category but it gives me empty products array. Am I missing something? version "mongoose": "^5.12.1",

Try to do that

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

I thought Mongoose ORM is automatically find relation with category and products. Mongoose needed product array on category to find relationship. So I added to products array to category doc. Now its working. tnx all..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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