Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

288
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda