0

Reading the mongo docs for modeling many-to-many relationships, I see they are using simple strings for the _id

{
   _id: "oreilly",
   name: "O'Reilly Media",
   founded: 1980,
   location: "CA"
}

{
   _id: 123456789,
   title: "MongoDB: The Definitive Guide",
   author: [ "Kristina Chodorow", "Mike Dirolf" ],
   published_date: ISODate("2010-09-24"),
   pages: 216,
   language: "English",
   publisher_id: "oreilly"
}

where I imagined it was beneficial to use actual ObjectId values as per this question: Difference between storing an ObjectId and its string form, in MongoDB

I’m finding it complex to have to cast between the object and string as this data passes back and forth between the Frontend (Vue) and backend (NestJS/Node) as JSON and am wondering if there is any real necessity to concern myself with utilizing ObjectId as it adds a fair bit of complexity.

Does storing the reference id as a string make any difference when performing an aggregation/$graphLookup? Am I meant to actually store this reference itself as an ObjectId or is that wholly unnecessary?

waffl
  • 5,179
  • 10
  • 73
  • 123
  • The answer to the question you referenced already answers your question. – D. SM May 26 '20 at 23:41
  • I’m not sure if it matters but I believe the other question speaks to the _id itself. I was wondering if there is any need to store the reference as ObjectId as well or is it basically a blanket rule that every ObjectId should always be stored as such and not a string. – waffl May 27 '20 at 06:43

1 Answers1

1

The only requirement for the values of _id is that they be unique as the _id is always indexed automatically by MongoDB and that index is unique.

The purpose of ObjectIDs is to allow the client to generate an ID that is guaranteed to be unique across a broad range of clients that are writing to the same collection. If you have a better unique ID you are encouraged to use it as it saves you an index. You do not need to cast that value into an ObjectID. It can be used in the clear as can other types (e.g. integers Decimals etc.).

Joe Drumgoole
  • 1,268
  • 9
  • 9