Search code examples
mongodbpymongo

bson.errors.InvalidId: '_id' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string


@app.route("/product/<id_product>", methods=["GET"])
def product(id_product):
    params = request.args    
    api_key = params["APIKEY"]
    if check_key(api_key):
        review = reviews.find_one(ObjectId(id_product), projection= {"comments": 0, "_id": 0, "user_image":0})
        product = products.find_one(ObjectId(id_product), projection= {"views": 0})
        products.update_one({"_id":ObjectId(id_product)}, {"$inc":{"views": 1}})
        return jsonify(product=product, reviews=review)
    else:
        return jsonify(ERROR="AUTHENTICATION PROBLEM USE VALID API KEY")

ERROR:
bson.errors.InvalidId: '626bccb9697a12204fb22ea30' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string

My code it gets a product_id from url product_id is _id of certain product in mongodb
FOR EXAMPLE :
id_product = 626bccb9697a12204fb22ea30
in mongodb my code should get document with _id = ObjectId(626bccb9697a12204fb22ea30)


I tried so many things but nothing worked !!!
what i think solution is that i have to convert string to a bytes instance
Even i tried to do this


@app.route("/product/<id_product>", methods=["GET"])
def product(id_product):
    params = request.args    
    api_key = params["APIKEY"]
    pro= bytes(id_product , "utf-8"))
    if check_key(api_key):
        review = reviews.find_one(ObjectId(pro), projection= {"comments": 0, "_id": 0, "user_image":0})
        product = products.find_one(ObjectId(pro), projection= {"views": 0})
        products.update_one({"_id":ObjectId(pro)}, {"$inc":{"views": 1}})
        return jsonify(product=product, reviews=review)
    else:
        return jsonify(ERROR="AUTHENTICATION PROBLEM USE VALID API KEY")

In this code i tried to convert string to bytes but doesn't work
ERROR:
TypeError: id must be an instance of (bytes, str, ObjectId), not <class 'bytes'>
Thanks in advance :)


Solution

  • Your objectId has 25 characters; if you make it 24 characters it will work.

    from pymongo import MongoClient
    from bson import ObjectId
    
    db = MongoClient()['mydatabase']
    
    db.mycollection.insert_one({
        "_id": ObjectId('626bccb9697a12204fb22ea3'),
        "key": "value"
    })