Hammad Khalid
Hammad Khalid

Reputation: 548

Python mongoengine - GET ID of the last entry

I have a scenario where i need to create a clone of few products in my mongoDB. I use the following code

    for single_product in survey_products:
        cloned_product = without_keys(single_product, {'_id'})
        cloned_product_doc = Product(**cloned_product)
        cloned_product_doc.save()
        print(cloned_product_doc.id)
        print(cloned_product_doc._id)

This creates the records properly which is alright, but in both the print functions, i get None even though i call cloned_product_doc.save() prior to accessing the IDs

How can i get the ID of the new entries?

EDITED

Here is the model definition

class Product(Document):
# model
_id = ObjectIdField()
photo = StringField()
name = StringField()
price = FloatField()
currency = StringField()

class Meta:
    db_table = 'product'

Upvotes: 2

Views: 698

Answers (2)

Abdullah Warraich
Abdullah Warraich

Reputation: 46

Edit the model definition like below, make sure you define the ObjectId as the default

.........................
from mongoengine import *
from bson import ObjectId
#import objectID to use as default

class Product(Document):
# model
_id = ObjectIdField(default=ObjectId)  # mention default as ObjectId
photo = StringField()
name = StringField()
price = FloatField()
currency = StringField()
class Meta:
    db_table = 'product'

Upvotes: 2

bagerard
bagerard

Reputation: 6354

Under normal usage, Mongoengine adds the id to the instance when you call .save().

from mongoengine import *

connect()

class MyDoc(Document):
    # Mongoengine adds an id = ObjectIdField if no 'id' is provided
    s = StringField()

doc = MyDoc(s='garbage').save()
print(doc.id)    # e.g 600df8c3d87af06b92725f87

I would suggest to inspect what is in your cloned_product. Perhaps there is a remaining 'id' key or something that interferes with default behavior

Upvotes: 1

Related Questions