Home > Software design >  MongoDB: Allow each user to have their own version of a shared document, keeping the ID
MongoDB: Allow each user to have their own version of a shared document, keeping the ID

Time:04-20

I have a MongoDB collection of Products that all users can view from a website, but I want to allow each user to edit these products' properties (name, price, etc.) while keeping the original ID.

Essentially each user would have their own version of this product, while still pointing to the same shared product everyone else uses. If possible the user would then fetch the Products collection, with the edited products replacing the "default" shared products (users most probably won't edit every product, so I'm trying to avoid just copying the whole collection for every user).

Is something like this doable? How would I structure it?

Example:

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) */

CodePudding user response:

Simply store users' modifications in embedded document based on user's id.

{
  id: "abc",
  name: "Car",
  price: 50000,
  modifications: {
    "1": {
      name: "Some car",
      price: 64000
    },
    "2": {
      name: "Red car",
      price: 48000
    }
  }
}

When querying, use aggregation pipeline to merge user specific values into global values:

var userId = 12345
db.cars.aggregate([
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: ["$$ROOT", `$modifications.${userId}`]
            }
        },
    },
    {
        $project: { modifications: 0 }
    }
])
  • Related