I'm just getting started with Flask_Pymongo (and pymongo in general). I wrote a simple test route that successfully inserts to my mongo db, however the return is not as expected. If I'm not mistaken pymongo should return the _id
field if I call inserted_id on the return. Seems like Flask_Pymongo is returning a collection object however:
@main.route('/')
def index():
user_collection = mongo.db.users
user_collection.insert_one({'name': 'Jack Black'})
print(user_collection.inserted_id)
return "<H2>Added a user!</H2>"
Returned object:
Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=False), 'example'), 'users.inserted_id')
The insert operation is successful otherwise and I see the new document with _id. What am I missing?
The correct way to get _id
is :
id = user_collection.insert_one({'name': 'Jack Black'}).inserted_id
print(id)
(Or)
userDoc = user_collection.insert_one({'name': 'Jack Black'})
print(userDoc.inserted_id)
Ref : pymongo-insert_one