我想在类别模型和产品模型之间定义一对多关系。
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
}
}
我有两个产品在这个类别,但它给了我空的产品阵列。我是不是错过了什么?版本";猫鼬":"5.12.1";,
我认为Mongoose ORM是自动找到与类别和产品的关系的。Mongoose需要类别上的产品数组来查找关系。所以我把产品数组添加到分类文档中。现在它开始工作了。tnx所有。。
尝试这样做
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))
}