node.js - Mongodb嵌套填充
问题描述
我在 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',
localField: '_id',
foreignField: 'user'
})
const User = mongoose.model('user', userSchema)
-----------
const Product = mongoose.model('product', {
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
quantity: {
type: Number,
default: -1
},
user: {
type: Schema.Types.ObjectId,
ref: 'user',
required: true
}
})
--------
const ItemSchema = new Schema({
session_id: {
type: String
},
quantity: {
type: Number,
required: true
},
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,
ref: 'user',
required: true
},
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 中的属性。虚拟通常用于文档上的计算属性。
您需要的一切都存储在数据库中,您无需计算任何东西。
推荐阅读
- python - 求 Maclaurin 级数从 0 到 1 的定积分
- docker - 尝试使用 Flask-mail 发送电子邮件时出现 SSL 错误
- mysql - MySQL 未在子查询连接中使用索引
- javascript - 单选按钮验证不起作用 jquery
- node.js - Adonis serve --dev 命令在 ubuntu 18.04 运行后立即停止
- autodesk-forge - SetThemingColor 隐藏元素
- imagej - 如何打开 .sav 扩展名 IDL 文件 imageJ?
- python - 如何使用 Python3 请求信任 badssl.com 的自签名证书
- java - Sikuli Windows Selenium Java 错误:致命错误 110:正在加载:WinUtil.dll
- python - 如果单词有连续的连字符,则使用 python 删除