我有带有嵌入式文档数组宠物的users.js模式。对于每个用户,用户可以拥有多只宠物(通常不超过3只)。
对于每只宠物,都会有一张日常图表。所以对于宠物来说,这将是许多日常图表。我已经阅读了嵌入式文档,每个数组元素都被编入索引。在daily.js中,如何引用populate()函数所属的宠物?
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
username: { type: String, required: true, unique: true },
location: String,
pets: [{ name: 'string', animalType: 'string'}], //could have more than one pet
created_at: Date,
updated_at: Date
});
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var dailySchema = new Schema({
tite: String,
_pet: { type: Number, ref: 'User.pet' }, // not sure how to reference name in user.pets[#] array
created_at: Date,
updated_at: Date
});
答案 0 :(得分:1)
很抱歉让人失望,但这是一种反模式。 Populate不能从另一个集合的subdocs填充 - 你得到该错误的原因是没有板的模型。
因此,引用嵌入式文档可能不是很好。最好将pet
与User
分隔为一个架构
var PetSchema = new Schema ({
name: 'string',
animalType: 'string'
});
UserSchema
和DailySchema
将是
var userSchema = new Schema({
...
pets: [{ type: Schema.Types.ObjectId, ref: 'Pet' }], //could have more than one pet
});
var dailySchema = new Schema({
_pet: { type: Number, ref: 'Pet' }, // not sure how to reference name in user.pets[#] array
});