Error getting MongoDB by _Id in Flask

北城余情 提交于 2021-02-10 20:22:43

问题


I can query my MongoDB and I see the "_id" value like this:

"_id" : BinData(3,"sFgVQWMKzUiWl5dql62j2g==")

Using Flask 0.10.1 and PyMongo 3.0.3 I attempt to "find_one" like this:

record = db.collection.find_one({'_id': ObjectId("sFgVQWMKzUiWl5dql62j2g==")})

And I get this error:

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

Any help would be appreciated.


回答1:


You are storing _id as bindata and trying to retrive it as ObjectId, instead of ObjectId.

First you need to convert your base64string to binary and then try to search.

bi = binary.Binary("sFgVQWMKzUiWl5dql62j2g==");
record = db.collection.find_one({'_id': bi});

This will work for you. It will convert your id to binary then compare to get result.




回答2:


Try this:

 record = db.collection.find_one({'_id': BinData(3, "sFgVQWMKzUiWl5dql62j2g==")})



回答3:


Ok here is how I got this working. From my PyMongo client I queried the result and got this:

_id: "497ffaf0-5ed3-3a4e-99ae-6b5c5f9b431e"

Note how that is not like the MongoDB console client which returns this:

_id : BinData(3,"sFgVQWMKzUiWl5dql62j2g==")

So seeing that the value looked like a GUID I started digging around and found that is a UUID and with that I did this:

import uuid
record = db.collection.find_one({'_id': uuid.UUID("497ffaf0-5ed3-3a4e-99ae-6b5c5f9b431e")})

This worked! Hazzah.




回答4:


Using Flask, MongoEngine I also was receiving errors searching by _id: mongoengine.errors.ValidationError: "DBRef('m_turk', ObjectId('5966b478b929570647f51a5c'))" is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string

In my case, the object id from MongoEngine.Document is of type bson.dbref.DBREF, whereas MongoEngine.Document expects type bson.objectid.ObjectId, despite returning bson.dbref.DBREF on MongoEngine.Document.objects(...).*. I'm not sure if this is an API inconsistency or simply my fault.

The fix was:

from flask_mongoengine import MongoEngine
from bson.objectid import ObjectId

... set Flask up ...

db = MongoEnginee(app)

class MiniFoo(db.Document):
       foo = db.StringField()

class MyDoc(db.Docment):
       key = db.StringField()
       myself = db.ReferenceField(MiniFoo)
       other_foos = db.ReferenceField(MiniFoo)

 myobj = MyDoc.objects.get(key="over the rainbow")
 # want to find other foos!

 # Will fail with exception above
 try:
     MiniFoo.objects.with_id(myobj.other_foos[0].id)
 except:
     MiniFoo.objects.with_id(ObjectId(obj.id))    



回答5:


with MongoEngine

from flask_mongoengine import MongoEngine
from bson.objectid import ObjectId

db = MongoEngine()
db.init_app(app)

class Model(db.Document):
    _id = db.ObjectIdField()
    name = db.StringField(required=True)

    @classmethod
    def findById(cls, _id: str):
        return cls.objects(_id=ObjectId(_id)).first()

modelById = Model.findById('601ec2d13ad7559bf7ebad76')


来源:https://stackoverflow.com/questions/31232422/error-getting-mongodb-by-id-in-flask

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!