lundi 18 novembre 2019

Insert ObjectId into mongodb

I'm working on a mongo database which, for some reason, has the user id stored as ObjectId.

In order to test some functions, I'd like to be able to populate a test database - for example, as follows:

import mongomock
from bson import ObjectId

client = mongomock.MongoClient("mongodb://localhost:27017/test-database")
database = client.get_default_database()
database.test_collection.insert({'_id': ObjectId('my_user_id'), 'value': 'my_value'})

However, running this returns

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

How can I correctly insert an ObjectId object into my test database, so I can test querying it using

database.test_collection.find_one({'user': ObjectId('my_user_id')})

(which works fine when I query the real database)?

Aucun commentaire:

Enregistrer un commentaire