问题描述
我在 MongoDB 中有 3 个集合,具有以下架构:
const userSchema = new Schema({
firstname: {
type: String,trim: true
},surname: {
type: String
}
})
userSchema.virtual('products',{
ref: 'product',localField: '_id',foreignField: 'user'
})
userSchema.virtual('carts',{
ref: 'cart',foreignField: 'user'
})
const User = mongoose.model('user',userSchema)
-----------
const Product = mongoose.model('product',{
title: {
type: String,required: true
},description: {
type: String,quantity: {
type: Number,default: -1
},user: {
type: Schema.Types.ObjectId,ref: 'user',required: true
}
})
--------
const ItemSchema = new Schema({
session_id: {
type: String
},price: {
type: Number
},total: {
type: Number
},product: {
type: Schema.Types.ObjectId,ref: 'product',required: true
}
})
const CartSchema = new Schema({
items: [ItemSchema],user: {
type: Schema.Types.ObjectId,total_price: {
type: Number,default: 0
}
})
const Cart = mongoose.model('cart',CartSchema)
假设我们在这些集合中有一些数据,我想像这样获取某个用户的购物车数据:
user = await User.findById(user_id).populate({
path: 'carts',populate: {
path: 'products',model: 'product'
}
})
return user.carts
我得到了以下回复,但没有提供产品详细信息:
[
{
"total_price": 10,"_id": "5ff373073b92a40898c50508","items": [
{
"_id": "5ff4d3b86404131811e392ef","product": "5fe9ea426c3ff17b383dd599","quantity": 5,"price": 2,"total": 10,"createdAt": "2021-01-05T21:01:44.269Z","updatedAt": "2021-01-05T21:01:44.269Z"
}
],"user": "5fe255a5543b7420c9c29c8b",}
]
如何获得产品详细信息,我对产品系列的结构是否正确?谢谢
解决方法
试试这个:
const userSchema = new Schema({
firstname: {
type: String,trim: true
},surname: {
type: String
},product: {
type: Schema.Types.ObjectId,ref: 'product',},cart: {
type: Schema.Types.ObjectId,ref: 'cart',})
对于您想要实现的目标,虚拟化应该不是必需的。
在 Mongoose 中,虚拟是不存储在 MongoDB 中的属性。 Virtuals 通常用于文档上的计算属性。
您需要的一切都存储在数据库中,您无需计算任何东西。