【发布时间】:2017-09-17 20:09:35
【问题描述】:
我有以下架构:
var WorkSchema = new Schema({
_id: Object, // {client: String, project: Number}
title: String,
description: String
});
var TimeWorkedSchema = new Schema({
_id: Object, // {client: String, date: Date}
work: {type: Object, ref: 'Work'}, // {client: String, proyect: Number}
hours: Number,
description: String
});
var w = mongoose.model('Work', WorkSchema);
var tw = mongoose.model('TimeWorked', TimeWorkedSchema);
字段Work._id 和TimeWorked.work 是具有相同属性的可比较对象。然后,我想像往常一样用相应的 Work 数据填充 TimeWorked 模型:
tw.find().populate('work').exec(function(err, res){
console.log(res);
});
打印:
[{
"_id": {
"client": "clientX",
"date": "2017-04-20T00:00:00.000Z"},
"work": {
"_id":{ ┐
"client": "clientX", |
"project": 1}, | invariable
"title": "ABC", |
"description": "defgh"}, ┘
"hours": 4,
"description": "bored"
},{
"_id": {
"client": "clientY",
"date": "2017-04-15T00:00:00.000Z"},
"work": {
"_id":{ ┐
"client": "clientX", |
"project": 1}, | invariable
"title": "ABC", |
"description": "defgh"}, ┘
"hours": 8,
"description": "funny"
},{...etc...}
]
如您所见,在所有返回的对象中,填充的 work 字段是同一个对象。
但是,如果我删除填充方法 (tw.find().exec(...)),我会得到原来的 work 字段,它们实际上是不同的。
我认为 Mongoose 没有实现这种类型的人口。如何关联两个模式以在查询中获取组合数据?
【问题讨论】:
标签: mongoose mongoose-populate