1 year ago

#318850

test-img

shan_pritc

How can I automatically append a unique field to element of a referenced array every time a new element is added to the source array?

Here's a simple example of what I'm after:

/* source array in clues collection: */ 
clues = [
  { title: "Islero", answer: 5 },
  { title: "Miura", answer: 17 },
];

/* user collection: */
{
 name: "Bob",
 userClues: [
  {/ref to clues[0]/, solved: true},
  {/ref to clues[1]/, solved: false}
]}

{
 name: "Wallace",
 userClues: [
  {/ref to clues[0]/, solved: true},
  {/ref to clues[2]/, solved: true}
]}

The primary "clues" array is to be updated and modified as needed, adding or removing clues and changing their values. The "userClues" array in each user's document is to exactly mirror the source clues array by reference, but I'd like to add an additional "solved" field to each element that is unique to each element in each "userClues" array. The "solved" field isn't linked or referenced to anything, each one stands alone. In this example, adding a third element to the "clues" array would add a third element to each "userClues" array along with it's own solved field for each user. Removing this third clue would also remove the entire third element from each "userClues" array.

I'm thinking a schema could be used to append the "solved" field automatically to each "userClues" element, but I'm not sure how you could spread the primary "clues" array into the "userClues" array by way of reference. Every example of referencing I've seen uses the '_id' to link the elements, so I don't see how a schema could apply to a pointer. Any advice or alternative solutions to this problem are greatly appreciated.

arrays

mongodb

reference

spread-syntax

0 Answers

Your Answer

Accepted video resources