POST 在 Postman 上使用 PyMongo 请求 TypeError

POST request TypeError with PyMongo on Postman

到目前为止,这是我的代码:

from flask import Flask, request, jsonify
from flask_pymongo import PyMongo, ObjectId
from flask_cors import CORS
import pymongo

app = Flask(__name__)
app.config["MONGO_URI"]="mongodb+srv://<USER>:<PASSWORD>...etc"
mongo = PyMongo(app)

CORS(app)

db = mongo.db.users

@app.route('/users', methods=['GET', 'POST'])
def createUser():
    if request.method == "GET":
            return jsonify({'msg': 'Successful GET response'})
    elif request.method == "POST":
        id = db.insert_one({
            'username': request.json['username'],
            'firstName': request.json['firstName'],
            'lastName': request.json['lastName'],
            'dob': request.json['dob']
        })
        return jsonify({'id': str(ObjectId(id)), 'msg': 'User Added Successfully!'})

#run app
if __name__ == "__main__":
    app.run(debug=True)

当我在 url“/users”尝试对 Postman 发出 POST 请求时,它给我以下 500 错误响应:

TypeError: id must be an instance of (bytes, str, ObjectId), not <class 'pymongo.results.InsertOneResult'>

我正在学习使用 .insert() 而不是更新的 .insert_one() 或 .insert_many() 的教程,我想知道这是否与问题有任何关系。

感谢任何帮助!

我明白了。我所要做的就是切换

return jsonify({'id': str(ObjectId(id)), 'msg': 'User Added Successfully!'})

return jsonify({'id': str(id.inserted_id), 'msg': 'User Added Successfully!'})

邮递员回复:

{
"id": "6[...]b",
"msg": "User Added Successfully!"
}