我正在尝试保存和检索具有关联游戏的游戏匹配集合,以及在其中玩游戏的人。我的模式是这样的,
const TournamentSchema = new mongoose.Schema({
matches: [{
games: [{
type: mongoose.Schema.Types.Mixed,
ref: 'Game',
players: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Player',
}],
}],
}],
});这是数据库中的对象的样子,
{
"__v": 0,
"_id": "5a50ed6b267ddd32c4523327",
"matches": [
{
"_id": "5a50ed6b267ddd32c4523328",
"games": [
{
"players": [
{ "_id": "5a4fa908d9d55465ac4fdbe6" },
{ "_id": "5a50cf3d09176c2bb0f98fe1" }
],
"_id": "5a498918ffc6220edbe8a403"
},
{
"players": [
{ "_id": "5a50cf5609176c2bb0f98fe2" },
{ "_id": "5a50cf6009176c2bb0f98fe3" }
],
"_id": "5a50cf9007c2bb0c73f3783a"
}
]
}
],
}我试着像这样找回它,
async function list(req, res, next) {
logger.log('info', 'Incoming request to retrieve all tournaments');
const tournaments = await Tournament.find().populate('matches.games.players');
return res.json(tournaments);
}但是,我从数据库中获得的内容与保存的内容相同。也就是说,裁判不会得到解决。如果我将type: Mixed从games更改为type: ObjectId,它将不会持久化players,但populate将解析games。如何使用refs中的refs?
根据请求,这是我的Game模式的样子,
const GameSchema = new mongoose.Schema({
name: {
type: String,
unique: true,
required: true,
lowercase: true,
},
scoring: {
type: Object,
required: true,
rank: {
first_place: Number,
second_place: Number,
third_place: Number,
},
},
max_num_players: Number,
min_num_players: Number,
}, { runSettersOnQuery: true });每个Game的每个等级可以有不同的scoring百分比。例如,对于反击,如果你是第一名,你会得到100%的分数,第二名是80%,第三名是50%。但是,对英雄联盟来说,第一名是85%,第二名是60%,第三名是50%。
发布于 2018-01-07 00:43:00
我认为问题在于您将游戏集合中的游戏定义和锦标赛游戏(实际上是游戏+玩家)都命名为“游戏”。
我会这样写模式(未测试):
const TournamentSchema = new mongoose.Schema({
matches: [{
games: [{
game: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Game',
},
players: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Player',
}],
}],
}],
});您可以像这样查询:
Tournament.find().populate('matches.games.game matches.games.players')
我仍然不清楚Game模式包含什么,以及为什么Game本身没有球员列表。
发布于 2022-01-26 04:24:58
也许有点晚了,但我会分享我通过研究一个类似的嵌套填充案例而理解到的东西(正如标题所说)。在documentation中,它说你可以用这种方式解决多个层次的人口问题:我们有一个模式:
const CustomerSchema = new Schema({
orders: [
{
type: Schema.Types.ObjectId || null,
ref: "Order",
},
],
(...)
})但同时的订单都有产品编号:
const OrderSchema = new Schema({
products: {
type: [{ type: Schema.Types.ObjectId, ref: "Product" }],
},
(...)
});现在你可以像这样做一个深度的群体:
const user = await CustomerModel.findById(id)
.populate("user", "-password")
.populate({ path: "orders", populate: { path: "products" } }) <---
.exec();希望这对有类似情况的人有所帮助。
https://stackoverflow.com/questions/48129054
复制相似问题