2

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:password@atlas.azure.mongodb.net')
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.

2 Answers2

0

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())
0

The problem is with this part:

# umongo motor connection
instance = Instance(db)

umongo.Instace is an abstract class and it's used to be implemented, not to be used directly.
You should use PymongoInstance, MotorAsyncIOInstance which are the implementation of Instance class for Pymongo and Motor drivers, respectively.

Here you should use MotorAsyncIOInstance when you want to use Motor driver.

Instead of the above snippet, use the below snippet and it'll do the job.

from umongo.frameworks import MotorAsyncIOInstance
instance = MotorAsyncIOInstance(db)