SourceCodeofMongoRedis
SourceCodeofMongoRedis copied to clipboard
[chapter_4]修复如果mongoDB没有数据时,第一次插入信息会报错
现象
当MongoDB没有数据时,第一次“添加人员”会报错。
IndexError: no such item for Cursor instance
原因
定位在anwer/DataBaseManager.DataBaseManager中的_query_last_id。
def _query_last_id(self):
last_info = self.handler.find({}, {'_id': 0, 'id': 1}).sort('id', -1).limit(1)
return last_info[0]['id'] if last_info else 0 # last_info是一个cursor,不管有没有数据,if last_info都为True。
解决办法
return last_info[0]['id'] if last_info.count() else 0