我正在开发一个 Flask 应用程序并使用 mongodb。在一个端点中,我获取了 csv 文件并将内容插入到 mongodb 中insert_many()
。在插入之前,我创建一个唯一索引以防止 mongodb 上的重复。当没有重复时我可以到达inserted_ids
对于该过程,但是当它引发重复错误时,我得到None
我无法得到inserted_ids
。我在用ordered=False
还。有什么方法可以让我得到inserted_ids
即使有重复密钥错误?
def createBulk(): #in controller
identity = get_jwt_identity()
try:
csv_file = request.files['csv']
insertedResult = ProductService(identity).create_product_bulk(csv_file)
print(insertedResult) # this result is None when get Duplicate Key Error
threading.Thread(target=ProductService(identity).sendInsertedItemsToEventCollector,args=(insertedResult,)).start()
return json_response(True,status=200)
except Exception as e:
print("insertedResultErr -> ",str(e))
return json_response({'error':str(e)},400)
def create_product_bulk(self,products): # in service
data_frame = read_csv(products)
data_json = data_frame.to_json(orient="records",force_ascii=False)
try:
return self.repo_client.create_bulk(loads(data_json))
except bulkErr as e:
print(str(e))
pass
except DuplicateKeyError as e:
print(str(e))
pass
def create_bulk(self, products): # in repo
self.checkCollectionName()
self.db.get_collection(name=self.collection_name).create_index('barcode',unique=True)
return self.db.get_collection(name=self.collection_name).insert_many(products,ordered=False)