我的Schema
看起来像这样,其中关联的是String
而不是_id
的数组,而我使用Virtual
方法填充了另一个{{ 1}}
Schema
我的const DetailSchema = mongoose.Schema({
candidate:{
.
.
associated: [String],
.
.
}
}, { toObject: { virtuals: true }, toJSON: { virtuals: true } });
看起来像
Virtual
返回的字段始终为DetailSchema.virtual('associatedJobs', {
ref: 'Jobs',
localField: 'candidate.associated',
foreignField: 'jobID',
justOne: false
});
。有什么问题吗?
答案 0 :(得分:1)
您应该同时提及两种架构结构以在查询中找到错误,我在虚拟字段中发表了一些示例,也许您会获得帮助
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/test', { useMongoClient: true });
var PersonSchema = new mongoose.Schema({
name: String,
band: String
});
var BandSchema = new mongoose.Schema({
name: String
}, { toObject: { virtuals: true } });
BandSchema.virtual('members', {
ref: 'Person', // The model to use
localField: 'name', // Find people where `localField`
foreignField: 'band', // is equal to `foreignField`
// If `justOne` is true, 'members' will be a single doc as opposed to
// an array. `justOne` is false by default.
justOne: false
});
var Person = mongoose.model('Person', PersonSchema);
var Band = mongoose.model('Band', BandSchema);
答案 1 :(得分:1)
您对Jobs
(ref: 'Jobs',
)的引用,如果您声明模型为Job
(可能不包含,则可能是ref: 'Job',
(Job
) ')
您的associatedJobs
将不在对象中返回,这是示例,它可能采用以下格式:
{
"candidate": {
"associated": [
"J2",
"J3",
"J5"
]
},
"_id": "5c1b4ab6683beb0b8162c80f",
"id": "D1",
"__v": 0,
"associatedJobs": [
{
"_id": "5c1b4ab6683beb0b8162c80b",
"jobID": "J2",
"name": "Job name 2",
"__v": 0
},
{
"_id": "5c1b4ab6683beb0b8162c80c",
"jobID": "J3",
"name": "Job name 3",
"__v": 0
},
{
"_id": "5c1b4ab6683beb0b8162c80e",
"jobID": "J5",
"name": "Job name 5",
"__v": 0
}
]
}
这是我为您解决的问题的解决方案,您可以在gist上下载以在本地https://gist.github.com/huynhsamha/a728afc3f0010e49741ca627750585a0上运行
我的简单模式作为您的模式:
var DetailSchema = new Schema({
id: String,
candidate: {
associated: [String]
}
}, {
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
var JobSchema = new Schema({
jobID: String,
name: String
});
DetailSchema.virtual('associatedJobs', {
ref: 'Job',
localField: 'candidate.associated',
foreignField: 'jobID',
justOne: false
});
var Detail = mongoose.model('Detail', DetailSchema);
var Job = mongoose.model('Job', JobSchema);
并且您应该在populate
时添加 find
:
const d = await Detail.findOne({ id: 'D1' }).populate('associatedJobs');