#python #mongodb #flask #crud
#python #mongodb #flask #crud
Вопрос:
Моя коллекция: db_operations = mongo.db.users
Я создаю пользователя с помощью этого метода:
@app.route('/create')
def create():
new_user = {'Name' : 'xyz', 'Age' : 20}
db_operations.insert_one(new_user)
#print(user['Name'],'Created successfully')
result = {'result' : 'Created successfully'}
return result
Когда я пытаюсь получить созданных мной пользователей, я получаю сообщение об ошибке KeyError: «Возраст», и ничего не отображается.
@app.route('/read')
def read():
users = db_operations.find()
output = [{'Name' : user['Name'], 'Age' : user['Age']} for user in users]
#print(output)
return jsonify(output)
Атлас Mongodb:
{«_id»:{«$oid»:»5fc22e0cade860ce44ec0541″}, «Name»:»xyz»,»Age»:{«$numberInt»:»20″}}
Другой метод, чтение с фильтром, работает отлично, отображает коллекцию в браузере.
@app.route('/read-with-filter')
def read_with_filter():
filt = {'Name' : 'xyz'}
users = db_operations.find(filt)
output = [{'Name' : user['Name'], 'Age' : user['Age']} for user in users]
#print(output)
return jsonify(output)
Ответ №1:
Если вы получите сообщение об ошибке
KeyError: 'Age'
это означает, что ключ Age
не существует. В вашем случае это означает, что переменная users
не содержит того, что вы думаете, что она делает. Так что проблема, на мой взгляд, может быть только здесь
users = db_operations.find()
Попробуйте print
вернуть, например
print(db_operations.find())
или
users = db_operations.find()
for user in users:
print(user)
и вы, вероятно, решите проблему самостоятельно.
HTH!