using Python to insert_one to my mongo_db, How do I pass key values into a function?

33 views Asked by At

I had a working function to insert a new doc in my database but I reviewed my assignment and the instructions want a function that takes args, when I re-wrote the code I get a type error.

(working code)

    def create():
        
        new_animal = {'animal_id': input('Enter animal_id'), 
  'rec_num': input('Enter rec_num'),
  'age_upon_outcome': input('Enter age_upon_outcome')}
        print(new_animal)
        
        animals_collection = DbTools.db.animals
       
    
        result = animals_collection.insert_one(new_animal)
    
        document_id = result.inserted_id
        print(f"_id of inserted document: {document_id}")
        print(new_animal)

        document_to_find = {'_id': ObjectId(document_id)}
        result = animals_collection.find_one(document_id)
        print("Found :", document_id)
        print(result)

re wrote to this to align with assignment requirements "Input argument to function will be a set of key/value pairs in the data type acceptable to the MongoDB driver insert API call" (Main.py)

import CRUD

   
CRUD


new_animal = {
  'animal_id': input('Enter animal_id'), 
  'rec_num': input('Enter rec_num'),
  'age_upon_outcome': input('Enter age_upon_outcome')}

for key,val in new_animal.items():
    CRUD.DbTools.create(key,val)

(CRUD.py)

    def create(key, value):
        
        new_animal = {key, value}
        print(new_animal)
        
        animals_collection = DbTools.db.animals
       
    
        result = animals_collection.insert_one(new_animal)
    
        document_id = result.inserted_id
        print(f"_id of inserted document: {document_id}")
        print(new_animal)

        document_to_find = {'_id': ObjectId(document_id)}
        result = animals_collection.find_one(document_id)
        print("Found :", document_id)
        print(result)

Output:

Pinged your deployment. You successfully connected to MongoDB!
Enter animal_id111
Enter rec_num222
Enter age_upon_outcome333
{'111', 'animal_id'}
Traceback (most recent call last):
  File "/Users/CS340WS/Main.py", line 28, in <module>
    CRUD.DbTools.create(key,val)
  File "/Users/CS340WS/CRUD.py", line 34, in create
    result = animals_collection.insert_one(new_animal)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/CS340WS/venv/lib/python3.11/site-packages/pymongo/collection.py", line 663, in insert_one
    common.validate_is_document_type("document", document)
  File "/Users/CS340WS/venv/lib/python3.11/site-packages/pymongo/common.py", line 552, in validate_is_document_type
    raise TypeError(
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
0

There are 0 answers