【问题标题】:Update field to null in mongoengine在 mongoengine 中将字段更新为 null
【发布时间】:2020-12-22 14:46:28
【问题描述】:

我正在使用 mongoengine。我希望能够在数据库中将我的字段设置为空,例如。字符串为空。

我尝试了以下方法,在我看来,每当我通过 None 时,该字段被跳过并且我无法替换现有值。 这甚至可能吗?

if user.contact_phone_number == "":
    user.contact_phone_number = None

我的文档:

contact_phone_number = StringField(
    db_field="contactPhoneNumber",
    regex=RE_CONTACT_PHONE,
    unique=False,
    sparse=True,
    required=False,
    null=True
)

【问题讨论】:

    标签: python mongodb flask mongoengine


    【解决方案1】:

    将 StringField 设置为 None 没有任何问题,见下文

    from mongoengine import *
    
    connect()
    
    class TestDoc(Document):
        s = StringField()
    
    TestDoc(s='test').save()
    
    t = TestDoc.objects.first()
    assert t.s == 'test'
    
    t.s = ""
    t.save()
    
    t = TestDoc.objects.first()
    assert t.s is ""
    
    t.s = None
    t.save()
    
    t = TestDoc.objects.first()
    assert t.s is None
    

    【讨论】:

    • 我发现设置为 None 并没有像我预期的那样将 value 设置为 null,它只是删除了该字段,因此您可以稍后再次分配。
    猜你喜欢
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2020-12-02
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 2012-05-30
    相关资源
    最近更新 更多