diwmix
diwmix

Reputation: 9

Why is an "id" not from Mongodb automatically created, and how to disable it

{
  "_id": {
    "$oid": "65ea05dbaa907e05219c0934"
  },
  "id": 6,
  "title": "asd",
  "content": "asd",
  "author": "asd",
  "category": "asd",
  "createdAt": {
    "$date": "2024-03-07T20:21:52.000Z"
  }
}

I couldn’t find the answer to the question on the Internet and gpt

Upvotes: 0

Views: 66

Answers (1)

Chukwujiobi Canon
Chukwujiobi Canon

Reputation: 3935

For posterity. The _id field is created by the MongoDB server and used by the server so you cannot delete that by default. It is 12 bit binary data.

Nevertheless, this is not what the OP asked.

Why is an "id" not from Mongodb automatically created, and how to disable it

Djongo mimics Django’s ORM and so just like in Django, an AutoField (AUTOINCREMENT field) is implicitly added to your models. This is the id field you automatically get.

But if you explicitly add an ObjectIdField (internally sets primary_key as True), the implicitly created AutoField (AUTOINCREMENT field) will not be added.

class YourModel(models.Model):
    _id = models.ObjectIdField() # <—- no more id field after this.
    # •••Rest of your Model•••

Fun fact: using the ObjectIdField in your models will save you from calling Django migrations every time you create a new model.

Upvotes: 2

Related Questions