Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

286
Views
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'
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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'
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!