Home > Mobile >  '$set' is empty. How do I fix this?
'$set' is empty. How do I fix this?

Time:10-16

I am trying to test my CRUD code to show that the CRUD is working correctly and I keep getting errors each way I try to test the code. My current issue is in the ipnyb file as it says the '$set' for the updateData is empty and I am pulling my hair out trying to figure out how to fix it.

My CRUD py code is as follows:

import pymongo

from pymongo import MongoClient
from bson.objectid import ObjectId

class AnimalShelter(object):
    """ CRUD operations for Animal collection in MongoDB """

    def __init__(self, username, password):
        #Initializing the MongoClient. This helps to access the MongoDB databases and collections.
        self.client = MongoClient('mongodb://%s:%s@localhost:45344' % (username, password))
        #where xxxx is your unique port number
        self.database = self.client['AAC']
    
#Complete this create method to implement the C in CRUD.
    def create(self, data):
        if data is not None:
            insert = self.database.animals.insert(data) #data should be dictionary
        
        else:
            raise Exception("Nothing to save, because data parameter is empty")
            
#Create method to implement the R in CRUD.
    def read(self, searchData):
        if searchData:
            data = self.database.animals.find(searchData, {"_id": False})
        
        else:
            data = self.database.animals.find({}, {"_id": False})
        return data

#Create method to implement U in CRUD.
    def update(self, searchData, updateData):
        if searchData is not None:
            result = self.database.animals.update_many(searchData, {"$set": updateData})
        else:
            return "{}"
        return result.raw_result

#Create method to implement D in CRUD.
    def delete(self, deleteData):
        if deleteData is not None:
            result = self.database.animals.delete_many(deleteData)
        
        else:
            return "{}"
        return result.raw_result

This is the ipnyb test code file that I am trying to run in Jupyter Notebook:

from AnimalShelter import AnimalShelter

data = {}
lookup = {"animal_id": ""}

test = AnimalShelter("aacuser","French")

#test each function in the AnimalShelter class
success = test.create(data)
print(success)

result = test.read(data)
print(result)

success = test.update(data, {})
print(success)

success = test.delete(data)
print(success)

This is the error I receive when doing that test:

None
<pymongo.cursor.Cursor object at 0x7fbd805c2320>

---------------------------------------------------------------------------
WriteError                                Traceback (most recent call last)
<ipython-input-38-04266c6e390a> in <module>
     13 print(response)
     14 
---> 15 response = test_class.update(data, {})
     16 print(response)
     17 

~/AnimalShelter.py in update(self, searchData, updateData)
     33     def update(self, searchData, updateData):
     34         if searchData is not None:
---> 35             result = self.database.animals.update_many(searchData, {"$set": updateData})
     36         else:
     37             return "{}"

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/collection.py in update_many(self, filter, update, upsert, array_filters, bypass_document_validation, collation, session)
   1074                 bypass_doc_val=bypass_document_validation,
   1075                 collation=collation, array_filters=array_filters,
-> 1076                 session=session),
   1077             write_concern.acknowledged)
   1078 

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/collection.py in _update_retryable(self, criteria, document, upsert, check_keys, multi, manipulate, write_concern, op_id, ordered, bypass_doc_val, collation, array_filters, session)
    854         return self.__database.client._retryable_write(
    855             (write_concern or self.write_concern).acknowledged and not multi,
--> 856             _update, session)
    857 
    858     def replace_one(self, filter, replacement, upsert=False,

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/mongo_client.py in _retryable_write(self, retryable, func, session)
   1489         """Internal retryable write helper."""
   1490         with self._tmp_session(session) as s:
-> 1491             return self._retry_with_session(retryable, func, s, None)
   1492 
   1493     def _reset_server(self, address):

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/mongo_client.py in _retry_with_session(self, retryable, func, session, bulk)
   1382                             raise last_error
   1383                         retryable = False
-> 1384                     return func(session, sock_info, retryable)
   1385             except ServerSelectionTimeoutError:
   1386                 if is_retrying():

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/collection.py in _update(session, sock_info, retryable_write)
    850                 bypass_doc_val=bypass_doc_val, collation=collation,
    851                 array_filters=array_filters, session=session,
--> 852                 retryable_write=retryable_write)
    853 
    854         return self.__database.client._retryable_write(

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/collection.py in _update(self, sock_info, criteria, document, upsert, check_keys, multi, manipulate, write_concern, op_id, ordered, bypass_doc_val, collation, array_filters, session, retryable_write)
    821             client=self.__database.client,
    822             retryable_write=retryable_write).copy()
--> 823         _check_write_command_response(result)
    824         # Add the updatedExisting field for compatibility.
    825         if result.get('n') and 'upserted' not in result:

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/helpers.py in _check_write_command_response(result)
    219     write_errors = result.get("writeErrors")
    220     if write_errors:
--> 221         _raise_last_write_error(write_errors)
    222 
    223     error = result.get("writeConcernError")

/usr/local/anaconda/lib/python3.6/site-packages/pymongo/helpers.py in _raise_last_write_error(write_errors)
    201     if error.get("code") == 11000:
    202         raise DuplicateKeyError(error.get("errmsg"), 11000, error)
--> 203     raise WriteError(error.get("errmsg"), error.get("code"), error)
    204 
    205 

WriteError: '$set' is empty. You must specify a field like so: {$set: {<field>: ...}}

How would I fix this error?

CodePudding user response:

The top part of the stack trace pinpoints where your error is, where the ---> arrows are:

---> 15 response = test_class.update(data, {})
---> 35             result = self.database.animals.update_many(searchData, {"$set": updateData})

You are passing in {} as updateData which is not valid for the $set operation. You need to pass in a dictionary to determine which field to set the value to, e.g. {'Field': 'Value'}

  • Related