我有 users.js 架构,其中包含嵌入文档数组 pets。对于每个用户,一个用户可以拥有多个宠物(我认为通常不超过 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
});
最佳答案
Sorry to disappoint but that is an anti-pattern. Populate can't populate from another collection's subdocs - the reason why you're getting that error is that there's no model for boards.
因此,引用嵌入文档可能不是一个好的模式。最好将 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
});
关于node.js - Mongoose-如何引用嵌入文档元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34822320/