Mongodb
MongoDB |將嵌入文件插入文件時出現問題
我正在嘗試以嵌套格式插入數據。
我的模型片段(還有很多很多):
class LifetimeMode(db.EmbeddedDocument): meta = {'collection': 'lifetime_mode'} career = db.EmbeddedDocumentField(GameModeData) war = db.EmbeddedDocumentField(GameModeData) sd = db.EmbeddedDocumentField(GameModeData) dom = db.EmbeddedDocumentField(GameModeData) class LifetimeData(db.EmbeddedDocument): meta = {'collection': 'lifetime_data'} mode = db.EmbeddedDocumentField(LifetimeMode) class UserData(db.EmbeddedDocument): meta = {'collection': 'user_data'} timestamp = db.DateTimeField(default=datetime.utcnow) type = db.StringField() level = db.IntField() lifetime = db.EmbeddedDocumentField(LifetimeData) class User(db.Document): meta = {'collection': 'user'} public_id = db.UUIDField() gamer_id = db.StringField() user_data = db.EmbeddedDocumentField(UserData)
當我嘗試使用虛擬數據創建數據庫時,我遇到了無法解決的問題。我從外部 API 獲取數據。
lt_mode_data = data['lifetime']['mode'] # << This is the API returned data for mode, mode_data in lt_mode_data.items(): game_mode_data = GameModeData() lifetime_mode = LifetimeMode() json_data = json.dumps(mode_data['properties']) lifetime_mode[mode] = game_mode_data.from_json(json_data)
問題是只添加了最終模式,好像每個模式數據都被添加但隨後被下一個模式覆蓋。
有任何想法嗎?
為了解決這個問題,我將程式碼更改為以下內容:
lt_mode_data = data['lifetime']['mode'] mode_dict = {} game_mode_data = GameModeData() lifetime_mode = LifetimeMode() for index, (mode, mode_data) in enumerate(lt_mode_data.items()): mode_dict[mode] = mode_data['properties'] lifetime_mode = lifetime_mode.from_json(game_mode_data.from_json(json.dumps(mode_dict)).to_json())