问题描述
情况:
我有一个包含3个集合的简单数据库:用户,运行,订单。
订单包含〜orderItems〜运行,用户可以一次购买多个运行。
我的主要问题:
当我更新order.isPaid === true
时,是否可以使用MongoDB自动交叉填充集合。我想填充当前正在传递的相同字段。
以下是实际行为:
order.orderItems = [{runObj}]
user.runs = [{runId}]
run.users = [{userObj}]
const orderSchema = mongoose.Schema({
orderItems: [
{
name: { type: String,required: true },location: { type: String,date: { type: String,price: { type: Number,run: {
type: mongoose.Schema.Types.ObjectId,required: true,ref: "Run",},],})
const runSchema = mongoose.Schema({
users: [
{
userId: {
type: mongoose.Schema.Types.ObjectId,ref: "User",username: {
type: String,profilePhoto: {
type: String,]
})
const userSchema = mongoose.Schema({
runs: [
{
runId: {
type: mongoose.Schema.Types.ObjectId,})
下面的此功能有效,但我想更好地了解我的Schema / Models和refs。
在相同请求下,在Stripe上成功签出并访问数据库。
-
更新创建的订单(
order.isPaid === true
) -
异步调用updateRunsAndUser(orderItems,userId)
const updateRunsAndUser = async (orderItems,userId) => { const user = await User.findById(userId); for (let i = 0; i < orderItems.length; i++) { const item = orderItems[i]; const run = await Run.findById(item.run); const runId = run._id; user.runs.push({ runId }); run.users.push({ userId,username: user.username,profilePhoto: user.profilePhoto,}); await user.save(); await run.save(); } };
-
使用userId参数并依次遍历orderItems,将用户按顺序(即Order.orderItems)添加到每个Run中。
-
使用成功消息
/
重定向到order.isPaid == true
,已添加用户以运行,运行中也包含用户。
产生的行为:(消除不相关对象的属性):
sampleOrderAfterCheckout = {
"_id": { "$oid": "5fa43b8624b3da0a5d02797d" },"orderItems": [
{
"_id": { "$oid": "5fa43b8624b3da0a5d02797e" },"run": { "$oid": "5fa436adf1047f07cc1af8d1" },"name": "Wednesday Night Run","price": 10,"location": "The Post","date": "11-04-2020"
}
],}
sampleRunAfterCheckout = {
"_id": { "$oid": "5fa436adf1047f07cc1af8d1" },"users": [
{
"_id": { "$oid": "5fa43b9124b3da0a5d027980" },"userId": { "$oid": "5fa436adf1047f07cc1af8cd" },"username": "merkyoass"
},}
sampleUserAfterCheckout = {
"_id": { "$oid": "5fa436adf1047f07cc1af8cd" },"isAdmin": true,"username": "merkyoass","runs": [
{
"_id": { "$oid": "5fa43b9124b3da0a5d02797f" },"runId": { "$oid": "5fa436adf1047f07cc1af8d1" }
}
],}
在所有3个文档中都有 runId,
1. orderObj,
Order.orderItems[0].run === 5fa436adf1047f07cc1af8d1
2. runObj,
run._id === 5fa436adf1047f07cc1af8d1
3. userObj,
user.runs[0].runId === 5fa436adf1047f07cc1af8d1
我的主要问题之一是Order.orderItems[0]._id
和users.runs[0]._id
在哪里
从?在其他任何收藏集中都找不到它们
Order.orderItems = [
{
"_id": { "$oid": "5fa43b8624b3da0a5d02797e" },}
]
User.runs = [
{
"_id": { "$oid": "5fa43b9124b3da0a5d02797f" },"runId": { "$oid": "5fa436adf1047f07cc1af8d1" }
}
]
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)