1

How can I set value for __id field in mongo db using flask-MongoEngine? here is my code

db = MongoEngine(app)

class Book(db.Document):
    id = db.IntField(required = True)
    title = db.StringField(required = True)
    author = db.StringField(required = True)

def Create_record(title:str,author:str):
    book = Book()
    book.id = "123"
    book.title = title
    book.author = author

book.save()
Machavity
  • 30,841
  • 27
  • 92
  • 100
fahad991
  • 452
  • 3
  • 8

1 Answers1

2

The easiest is to rely on the auto-generated id's from MongoDB (ObjectID) which encapsulates a timestamp so it's quite handy. If you don't specify any primary key field in your model, MongoEngine adds id behind the scenes.

This would be defined as:

class Book(Document):
    title = StringField()

book = Book(title='foo')
book.save()

Which is equivalent to

class Book(Document):
    id = ObjectIdField(default=bson.ObjectId, primary_key=True)
    title = StringField()

book = Book(title='foo')    # MongoEngine takes care of the id
book.save()

If for some reason you want an auto-increment integer, instead of an object id, you can achieve this easily with MongoEngine's SequenceField:

class Book(Document):
    id = SequenceField(primary_key=True)
    title = StringField()

book = Book(title='foo')    # MongoEngine takes care of the id
book.save()

Or, if you really want to manage the primary key yourself, then you can do it with

class Book(Document):
    id = IntField(primary_key=True)
    title = StringField()
    author = StringField()

book = Book(id=123, title='foo')
book.save()

What was missing in your example was the primary_key=True in the field definition

bagerard
  • 5,681
  • 3
  • 24
  • 48