mongoengine save method is deprecated?

2019-08-01 10:15发布

问题:

I wonder why my python says that mongoengine save() method is deprecated? I don't see any info about this into official documentation https://mongoengine.readthedocs.io/en/v0.9.0/apireference.html

class MyModel(Document):
    user_id = StringField(required=True)
    date = DateTimeField(required=True, default=datetime.datetime.now)

my = MyModel()
my.user_id = 'user'
my.save()

and now i see:

/Library/Python/2.7/site-packages/mongoengine/document.py:340: DeprecationWarning: save is deprecated. Use insert_one or replace_one instead

I've python 2.7 and also installed pymongo, mongoengine and bottle-mongo (maybe some issues with that?)

回答1:

MongoEngine wraps PyMongo, which deprecated "save" in PyMongo 3.0:

http://api.mongodb.com/python/current/changelog.html#collection-changes

MongoEngine might need to deprecate its save method, or suppress the deprecation warning, or perhaps some other fix to handle this PyMongo change. I recommend you search MongoEngine's bug tracker and report this issue if it has not been already.

MongoEngine Bug - https://github.com/MongoEngine/mongoengine/issues/1491



回答2:

Using col.replace_one({‘_id': doc['_id']}, doc, True) instead.

The api is replace_one(filter, replacement, upsert=False, bypass_document_validation=False, collation=None, session=None).

Using upsert = True to insert a new doc if the filter find nothing.