【发布时间】:2019-01-25 16:37:49
【问题描述】:
我有点坚持试图找出在我的数据库中填充虚拟模式的最佳方法。在这种情况下,我想检查多个字段,但我不知道任何方法或替代方法。
我曾希望我可以在虚拟模式的“localField”和“foreignField”键中使用一些字符串数组,但事实并非如此。
用户保存了一个“系列”_id,虚拟模式“联赛”也获取了用户输入的所有联赛,捕获的是一个联赛属于不同的系列。我只想检索用户输入的联赛以及与用户的系列_id匹配的联赛......
正如您目前所看到的,此虚拟模式仅返回用户输入的所有联赛,而与系列无关。 :(
有什么想法吗?我一直很困惑如何实现这一目标。
const schema: mongoose.Schema = new mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
auto: true
},
username: {
type: String,
unique: true,
},
series: {
ref: 'Serie',
type: mongoose.Schema.Types.ObjectId,
autopopulate: {
maxDepth: 1,
select: ['title']
}
}
});
schema.virtual('leagues', {
ref: 'League',
localField: '_id',
foreignField: 'users',
autopopulate: {
maxDepth: 1,
select: ['title', 'engineSize', 'host', 'series']
}
});
联赛架构如下所示
const schema: mongoose.Schema = new mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
auto: true
},
title: String,
series: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Serie',
},
users: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
}]
});
【问题讨论】:
标签: node.js mongodb mongoose mongoose-schema mongoose-populate