【发布时间】: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