Is it possible to add custom field when we create a collection. Something like this:
db.createCollection("myCollection", {my_custom_field: "some value"})
The idea is, some users can create collections and add data. But I want to know which user the collection belongs to. So I need to add some metadata about the collection.
CodePudding user response:
You could create something like an abstract type where the base class has the user_id and each document extends that type. Your document would look something like this:
{
user_id: "id",
my_custom_value: <object or value>
}
Essentially, just add your metadata to the root of the document and the user defined value under that. Doing it this way means you wouldn't have a collection per user, you would have a single collection that allows users to add custom values.
If you do really need a collection per user then you might be able to just append the user_id to the collection name, but this seems like an anti-pattern and I would recommend first trying to create a single collection that meets your requirements:
db.createCollection("myCollection_<user_id>", {my_custom_field: "some value"})