我已经尝试过要求这个问题,但我想我没有明确表示没有人回答过,所以我将在这里给出一些具体代码的特定场景。
上下文很简单,让我们想象一下每周一次的锦标赛,每场锦标赛都由游戏组成,由玩家组成。
所以我们有3个模式:
TournamentSchema {
Games: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Game' } ]
Players: [
{
_user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
points: { type: Number }
}
] //The total amount of points the user made for this tournament
}
GameSchema {
Players: [
{
_user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
points: { type: Number }
}
] //The total amount of points the user made for this specific game
}
PlayerSchema {
pseudo: { type: String },
email: { type: String },
points: { type: Number } // The total amount the player made
// (on every tournaments).
}
这里的一切都很好。
每次客户端想要显示排名(find()
按点排序)时,要不按点数请求sort()
et Tournament.Players collection
,我将锦标赛实例保留在特定模块中(所以我可以只slice()
我需要处理的有序Players collection
部分。
所以每次玩家加入游戏时,我都必须:
Tournament.Players collection
并保存。问题是,我无法将Model
推入Tournamanent.Players collection
,我想猫鼬无法管理它(Player Model
变为ObjectID
一次插入):
var NewPlayer = new PlayerSchema(
{ pseudo: 'warior', email: 'warioir@something.com' }
);
Tournament.Players.push({ _user: NewPlayer, points: 0 })
//add an item: { _user: <ID>, _id: <ID>, points: 0 } pseudo?? email??
因此,当我将一个完整的模型播放器推入填充的锦标赛玩家系列时,它就变成了一个ObjectID。
我的问题就在这里,因为在那之后我有一个Tournament.Players
集合,其中包含人口众多和未经填充的玩家,管理起来很痛苦!
所以我现在所做的是,每次我推动一个玩家模型时,我会在整个锦标赛中使用一个填充类创建一个新的find()并用我刚刚得到的那个替换我的旧实例,但这对于一个非常重要的操作具体需要。
您将如何管理这种情况(需要在存储在模块中的已填充集合上添加模型)?
答案 0 :(得分:0)
我分两步完成。当新玩家加入时,在User表中创建一个条目,获取该_id,然后将其插入Game and Tournament集合中。猫鼬并不像你过去使用的其他ORM那样“神奇”。我最近进行了1k行更改以从项目中删除mongoose并改为使用本机驱动程序。