mongoengine icon indicating copy to clipboard operation
mongoengine copied to clipboard

cascade_save does not save new referenced document

Open lafrech opened this issue 9 years ago • 14 comments

When saving a document with a ReferenceField holding a new object, I get an error:

mongoengine.errors.ValidationError: ValidationError 
You can only reference documents once they have been saved to the database

I naively expected cascade=True to automatically save the new document, while apparently it only automatically saves changes to existing documents.

Is this something that could be changed or is it meant to be for good reasons?

Example:

    class User(Document):
        name = StringField()

    class UserSubscription(Document):
        name = StringField()
        user = ReferenceField(User, dbref=False)

    User.drop_collection()
    UserSubscription.drop_collection()

    # u1 = User(name="Ross").save()
    u1 = User(name="Ross")

    sub = UserSubscription(user=u1).save()

I'd like this not to throw ValidationError but to save u1 in cascade.

lafrech avatar Feb 18 '16 11:02 lafrech

I have the same problem. doc.save(cascade=True) does not save any documents unless they already exist, and doc.cascade_save() does not save the document itself.

Kobnar avatar May 11 '16 15:05 Kobnar

Hi. Any news on this ? It seems like the bug is still there.

celestianx avatar Apr 18 '17 19:04 celestianx

Get the same behaviour here with MongoEngine 0.11.0.

  • save(cascade=True) doesn't actually seem to do cascade saving (still gives the same errors as without cascade=True)
  • save_cascade() does not save the document itself

NiklasRosenstein avatar Jun 25 '17 11:06 NiklasRosenstein

I have the same problem reported here, save(cascade=True) doesn't work and thus saving the parent document throws a ValidationError.

doaa-altarawy avatar Oct 18 '18 18:10 doaa-altarawy

Same issue here.

shenin04 avatar Oct 24 '18 14:10 shenin04

+1 bumping this, it would be great to be able to save new embedded documents as references without having to dig into the substructure of the parent document to save all the new objects.

ewengillies avatar Feb 08 '19 13:02 ewengillies

+1 bumping this. How is this still open after four years?

burchill avatar Apr 07 '20 22:04 burchill

+1

DonQueso89 avatar Apr 24 '20 12:04 DonQueso89

+1 once again. Having to override the save method on all my classes is a massive PITA. Here's the method that I usually use if anyone wants it. Replace self.refs with your ReferenceFields.

def save(self, *args, **kwargs):
    for ref in self.refs.values():
        ref.save()
    return super().save(*args, **kwargs)

DataKinds avatar Jun 24 '20 03:06 DataKinds

+1

Evisolpxe avatar Oct 12 '20 15:10 Evisolpxe

+1

OliverLSanz avatar Feb 02 '21 11:02 OliverLSanz

+1

joeriddles avatar Jul 01 '21 20:07 joeriddles

Is this Issue solved?

mo-cmyk avatar Oct 21 '22 22:10 mo-cmyk

Is this solved?

NisugaJ avatar Oct 21 '23 16:10 NisugaJ