[FIXED] Autoincrement with MongoEngine

Issue

I'm developing a blog engine with Flask and MongoEngine, and I need sequential IDs for my posts.

I need MongoEngine to create a new ID for each new post, so I was thinking of doing something like this:

class Post(Document):
  title = StringField(required=True)
  content = StringField(required=True)
  published_at = datetime.utcnow()
  id = Post.objects.count() + 1

Will this work? is there a better way to do this?


Solution

Firstly, you need to understand why you need incremental id's? What do they solve?

Theres no native solution in mongoDB - please read: http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field

As you already have a unique identifier with the pk of the Post, why not use that?

Finally, if I haven't dissuaded you from folly, there is a SequenceField in mongoengine that handles incrementing for you.



Answered By - Ross
Answer Checked By - Senaida (Python.Easybugfix Volunteer)

Related Posts

Post a Comment