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.
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
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 indexbookmarks
fields it is not possible as the field names are changing.You can use something like this, for the
bookmarks
field: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).