Pymongo insert時會自動新增 id

2021-10-09 15:29:38 字數 2208 閱讀 2559

在使用pymongo時遇到了乙個小坑:

在flask框架中,將字典插入mongodb後再返回就報錯

'***x'

)def

main()

:...

data =

mycol.insert_one(data)

return data

traceback (most recent call last):

response = self.handle_exception(e)

reraise(exc_type, exc_value, tb)

file "/home/xiang/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise

raise value

response = self.full_dispatch_request()

return self.finalize_request(rv)

response = self.make_response(rv)

rv = jsonify(rv)

file "/home/xiang/.local/lib/python3.6/site-packages/flask/json/__init__.py", line 370, in jsonify

dumps(data, indent=indent, separators=separators) + "\n",

file "/home/xiang/.local/lib/python3.6/site-packages/flask/json/__init__.py", line 211, in dumps

rv = _json.dumps(obj, **kwargs)

file "/home/xiang/.local/lib/python3.6/site-packages/******json/__init__.py", line 412, in dumps

**kw).encode(obj)

file "/home/xiang/.local/lib/python3.6/site-packages/******json/encoder.py", line 298, in encode

chunks = list(chunks)

file "/home/xiang/.local/lib/python3.6/site-packages/******json/encoder.py", line 696, in _iterencode

for chunk in _iterencode_dict(o, _current_indent_level):

file "/home/xiang/.local/lib/python3.6/site-packages/******json/encoder.py", line 652, in _iterencode_dict

for chunk in chunks:

file "/home/xiang/.local/lib/python3.6/site-packages/******json/encoder.py", line 716, in _iterencode

o = _default(o)

file "/home/xiang/.local/lib/python3.6/site-packages/flask/json/__init__.py", line 100, in default

return _json.jsonencoder.default(self, o)

file "/home/xiang/.local/lib/python3.6/site-packages/******json/encoder.py", line 273, in default

o.__class__.__name__)

typeerror: object of type objectid is not json serializable

這是由於pymongo在進行插入操作時,如果字典中沒有『_id』,會自動新增『_id』,而它的值為objectid例項,flask在對返回值進行編碼時無法編碼objectid型別例項,所以報錯,解決辦法就是去掉『_id』或者mycol.insert_one(data.copy())

參考:

解決方法 Pymongo insert 卡住

先說一下標題,當我不知道問題的具體原因的時候,上面的標題就是我在搜尋引擎中輸入的內容。同樣的,我還嘗試過以下幾種搜尋組合 pymongo insert hangs pymongo insert stop pymongo insert no return mongodb insert hangs mo...

MySQL查詢何時會被阻塞

由於沒有拿到mdl讀鎖 可以通過show processlist命令檢視執行緒狀態為 waiting for table metadata lock,這時需要找到鎖住這個表的執行緒,通過select blocking pid from sys.schema table lock waits,然後ki...

使用new時,會發生什麼?

使用new來呼叫函式,或者說發生構造函式呼叫時,會自動執行下面的操作 建立 或說構造 乙個全新的物件。這個新物件會被執行 prototype 連線。這個新物件會繫結到函式呼叫的this。如果函式沒有返回其他物件,那麼new表示式中的函式呼叫會自動返回這個新物件。如下 function fn var ...