'Using Motor with uMongo :: Always Getting None
I'm trying to figure out how to use uMongo with Monitor and I am having a problem. I can't get the uMongo document object to return anything other than None and I am sure it's something obvious I just keep overlooking. If anyone has any suggestions or can see something I don't please let me know.
The connection string was sanitized, it's not really like this in my code.
Here is the test file I'm using:
import asyncio, pprint
from motor.motor_asyncio import AsyncIOMotorClient
from umongo import Document, Instance, fields
# plain motor connection
client = AsyncIOMotorClient('mongodb+srv://user:[email protected]')
db = client.my_database
# umongo motor connection
instance = Instance(db)
# umongo document object
@instance.register
class User(Document):
nickname = fields.StringField()
gender = fields.StringField()
class Meta:
collection = db.test
# plain motor query function
async def plain_motor_find_one():
document = await db.test.find_one({'nickname': 'rook'}) # this works
pprint.pprint(document)
# umongo motor query function
async def umongo_motor_find_one():
document = await User.find_one({'nickname': 'rook'}) # this does not and returns None
pprint(document)
# grab event loop
loop = asyncio.get_event_loop()
# make our calls
loop.run_until_complete(plain_motor_find_one())
loop.run_until_complete(umongo_motor_find_one())
And here is what the object in my database.test collection looks like:
{
"_id" : ObjectId("5e8b9c205ac19a8a91658f17"),
"nickname" : "rook",
"gender" : "male"
}
Thank you very much.
Solution 1:[1]
If You want to use Motor and asynchronous, follow this code:
import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
from umongo import Document, fields
from umongo.frameworks import MotorAsyncIOInstance
client = AsyncIOMotorClient('mongodb://localhost:27017')
db = client.shop
instance = MotorAsyncIOInstance(db)
@instance.register
class User(Document):
name = fields.StringField()
class Meta:
collection = db.user
async def plain_motor_find_one():
document = await User.find_one({'foo': 'bar'}) # now all methods are awaitable
print(document)
loop = asyncio.get_event_loop()
loop.run_until_complete(plain_motor_find_one())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pygopher |