问题描述
我想在我的类别模型和产品模型之间定义一对多关系。
product.js(模型)
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
name:{
type:String,required:true
},price:{
type:Number,description:{
type:String,required:false
},imageUrl:{
type:String,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,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”,
解决方法
尝试这样做
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))
}
,
我认为 Mongoose ORM 会自动查找与类别和产品的关系。 Mongoose 需要类别上的产品数组来查找关系。所以我将产品数组添加到类别文档。现在它的工作。 tnx 全部..