我有一個所有用戶都可以從網站查看的產品的 MongoDB 集合,但我希望允許每個用戶在保留原始 ID 的同時編輯這些產品的屬性(名稱、價格等)。
本質上,每個用戶都有自己的產品版本,同時仍然指向其他人使用的同一個共享產品。如果可能,用戶然后會獲取 Products 集合,用編輯的產品替換“默認”共享產品(用戶很可能不會編輯每個產品,所以我試圖避免只為每個用戶復制整個集合)。
這樣的事情可行嗎?我將如何構建它?
例子:
ORIGINAL PRODUCT
id: abc
name: "Car"
price: 50000
USER 1
id: abc
name: "Some car"
price: 64000
USER 2
id: abc
name: "Red car"
price: 48000
/* These all refer to the same product (same id) */
uj5u.com熱心網友回復:
只需根據用戶的 id 將用戶的修改存盤在嵌入式檔案中。
{
id: "abc",
name: "Car",
price: 50000,
"modifications" : [
{
"user_id" : 1,
"name" : "Some car",
"price" : 64000.0
},
{
"user_id" : 2,
"name" : "Red car",
"price" : 48000.0
}
]
}
查詢時,使用聚合管道將用戶特定值合并為全域值:
var user_id = 1234
db.cars.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: {
$let: {
vars: {
userModifications: {
$first: {
$filter: {
input: "$modifications",
as: "modification",
cond: { $eq: ["$$modification.user_id", user_id] }
}
}
}
},
in: ["$$ROOT", "$$userModifications"]
}
}
}
},
},
{
$project: { modifications: 0 }
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459383.html
上一篇:嘗試讀取mongoDB檔案屬性
