Mongoose由ObjectId填充,其中在模式中的ObjectId之后还有另一个属性



我有一个Cart架构,定义如下:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const cartSchema = new Schema({
items:[
{
id:{
type:Schema.Types.ObjectId,
ref:'Post'
},
quantity:Number
}
]
});

Schema引用items数组中Post的另一个Schema的_id,以及购物车中该项目的数量。我对Cart的find语句包括一个populate()方法调用,从理论上引入实际的Post项,这样我就可以在页面上显示标题等:

let cart;
if(!req.session.cartId) {
req.session.error = 'There are no items currently in your cart';
return res.redirect('/');
}
try {
cart = await Cart.findById(req.session.cartId).populate({
path:'item',
model:'Post'
}).exec();

省略catch块,因为我不认为它是问题的一部分。我应该能够看到Post文档而不是它的ObjectId,并且我已经能够在其他地方执行类似的操作。

该语句运行并返回Cart,但populate()调用似乎被忽略了,我得到的只是items数组,其中的_idquantity值与我最初存储的值完全相同:

cart: {
_id: 5e6e884ffda1be0648ae1b99,
items: [ { _id: 5e3435f9ab899a1dd8a4105e, quantity: 1 } ],
__v: 1
}

然而,我看到的关于Mongoose.populate()的一切都是在当前(cart(文档中仅存储对外部(post(文档的ObjectId的引用,而没有quantity的附加属性。这就是给我带来问题的原因吗?如果是,我如何将Postitems中的数量链接到Cart中?

您的填充不正确。

您的路径必须是items.id而不是item,并且模型必须是实际的模型,而不是字符串,所以请删除单引号,并确保像const Post = require("../models/post");一样导入它

cart = await Cart.findById(req.session.cartId).populate({
path:'items.id',
model:Post
}).exec();

这会给你这样的结果:

{
"_id": "5e6f2dd63d82e35988921907",
"items": [
{
"_id": "5e6f2dd63d82e35988921909",
"id": {
"_id": "5e6f2da53d82e35988921905",
"title": "Post 1 Title",
"__v": 0
},
"quantity": 1
},
{
"_id": "5e6f2dd63d82e35988921908",
"id": {
"_id": "5e6f2db13d82e35988921906",
"title": "Post 2 Title",
"__v": 0
},
"quantity": 2
}
],
"__v": 0
}

由于id字段的原因,结果看起来有点难看,不容易读取。因此,我建议您将items.id字段重命名为items.post,如下所示:

const cartSchema = new Schema({
items: [
{
post: {
type: Schema.Types.ObjectId,
ref: "Post"
},
quantity: Number
}
]
});

并将填充路径更改为items.post,结果如下所示:

{
"_id": "5e6f2dd63d82e35988921907",
"items": [
{
"_id": "5e6f2dd63d82e35988921909",
"post": {
"_id": "5e6f2da53d82e35988921905",
"title": "Post 1 Title",
"__v": 0
},
"quantity": 1
},
{
"_id": "5e6f2dd63d82e35988921908",
"post": {
"_id": "5e6f2db13d82e35988921906",
"title": "Post 2 Title",
"__v": 0
},
"quantity": 2
}
],
"__v": 0
}

相关内容

最新更新