Home > OS >  Storing enum to MongoDb (for managing tag names)
Storing enum to MongoDb (for managing tag names)

Time:02-05

If we have a collection of books, we can assign tags of authors into an array as follows:

Books collection

{
    ...,
    "authors" : ["John Michaels", "Bill Williams"]
}

This can cause problems if an author's name changes.

Instead, I was thinking of assigning an integer value to each author and creating a 'tags' collection:

Tags collection

{
    “tags” : [
        {“John Michaels” : 0},
        {“Jane Collins” : 1},
        {“Bill Williams” : 2}
    ]
}

Here is my books collection, here we specify that ‘John Michaels’ and ‘Bill Williams’ are the authors:

{
    …,
    “authors” : [0, 2]
}

If I ever needed to change the author’s name ‘Bill Williams’ to ‘Bill H. Williams’, there would be no problem because the value stored in the books collection remains unchanged.

My Question is if MongoDB has something like enums that will automatically increment the integral value or if there is something else built into MongoDB to help with this type of situation.

Thank you

CodePudding user response:

This is typical use case of referencing other collections. So, you should have 2 collections:

Authors collection:

{
  _id: ObjectId,
  name: String,
  ... // Other fields
}

Books collection:

{
  _id: ObjectId,
  authors: [ ObjectId ], // References to documents from Author collection
  ... // Other fields
}

So, in authors property of the Books collection, you store _id values of all the authors. Then when you fetch book document, you can easily fetch up-to-date authors data from Authors collection.

  •  Tags:  
  • Related