Reputation: 936
I have this code:
def add_new_category(group_id: str, name: str) -> tuple:
"""
Used to add a new transaction category
:param group_id: str
:param name: str
:return: tuple of bool and result
"""
try:
current_app.logger.info("add_new_category function called ...")
if len(list(db.groups_categories.find())) == 0:
data = {
"group_id": group_id,
"categories": [{
"cat_id": ObjectId(),
"name": name,
"created_at": now
}]
}
result = db.groups_categories.insert_one(data).inserted_id
_d = db.groups_categories.find().sort('group_id', pymongo.ASCENDING).limit(1)
else:
result = db.groups_categories.update_one({"group_id": ObjectId(group_id)}, {"$push": {"categories": {
"cat_id": ObjectId(),
"name": name,
"created_at": now
}}})
_d = db.groups_categories.find().sort('group_id', pymongo.ASCENDING).limit(1)
except Exception as e:
current_app.logger.error(f"add_new_category error: {e}")
The function should initially add a record and subsequent operations should append an object to to categories array. The first part works but the second part gives no error but no object is appended.
I have been on this for over 24hrs and I can't seem to find why the second operation (update_one) is not working. Any pointers would really help.
Please note I am adding this data on an atlas instance from my localhost and using the pymongo library for mongodb.
Logs from the update_one operation:
In second else ...
[2022-06-15 09:11:49 +0100] [48333] [INFO] db_init Function called ...
M: []
[2022-06-15 09:11:51 +0100] [48333] [INFO] db_init Function called ...
[2022-06-15 09:11:54 +0100] [48333] [INFO] db_init Function called ...
REMADD:127.0.0.1 - USER:- RDATE:[15/Jun/2022:09:11:57 +0100] METHOD:POST URL:/api/v1.0/transactions/categories PROTO:HTTP/1.1 STATUS:200 UAGENT:PostmanRuntime/7.26.8 PID:<48333>
Check to see that the collection is empty and if so
Result(s):
The insertion operation works but push operation doesn't. No errors shown but the categories array isn't updated as expected.
Upvotes: 0
Views: 129
Reputation: 37048
Assuming group_id
in consecutive calls is the same you need to use it consistently.
You insert it as plain string in:
data = {"group_id": group_id,....}
db.groups_categories.insert_one(data)
And filter by an objectId generated from the string for update:
db.groups_categories.update_one({"group_id": ObjectId(group_id)},..
Mongo compare types, a string never equal to an object. There are no documents matching the filter argument, so update affects 0 documents.
Either use strings or ObkectIds in both queries.
All my comments to the OP are still valid. There are number of flaws in the code, so fixing this issue alone will result with unexpected results in specific conditions.
Upvotes: 1