Mongodb – Do you think using ObjectID as field name is a bad practice? What can go wrong if I follow this design

database-designmongodbmongodb-4.0schema

I design a MongoDB collection where I am planning to use mongo ObjectID as a field name. The ObjectID is a PostID and in the array, I track all the userID who liked or disliked the post.

enter image description here

Best Answer

Yes, it is not a good idea to use a dynamic (changing value) like an ObjectId as a field name. To query a specific bookmark you are looking for a specific value for a specific field. And also, to index bookmarks fields it is not possible as the field names are changing.

You can use something like this, for the bookmarks field:

bookmarks: [
    { post_id: "606182bff8a94f5405c45268", like_dislike_users: [ 3, 5, 8, 12 ] },
    { ... },
     ...
]

Where bookmarks is a field of type array. And, each element in the array is a sub-document (a.k.a. embedded document).

Now, you can query the bookmarks for posts or/and like/dislike users by their ids (see Query an Array of Embedded Documents). In addition, for an efficient querying you can index on these fields (indexes on array fields are known as Multikey Indexes).