Mongoose 支持dynamic references。您可以使用String 和refPath 指定类型。看一下documentation提供的schema示例:
var userSchema = new Schema({
name: String,
connections: [{
kind: String,
item: { type: ObjectId, refPath: 'connections.kind' }
}]
});
上面的 refPath 属性意味着 mongoose 会查看
connections.kind 路径,用于确定用于 populate() 的模型。
换句话说, refPath 属性使您能够使 ref
属性动态。
来自documentation 的示例,来自populate 调用:
// Say we have one organization:
// `{ _id: ObjectId('000000000000000000000001'), name: "Guns N' Roses", kind: 'Band' }`
// And two users:
// {
// _id: ObjectId('000000000000000000000002')
// name: 'Axl Rose',
// connections: [
// { kind: 'User', item: ObjectId('000000000000000000000003') },
// { kind: 'Organization', item: ObjectId('000000000000000000000001') }
// ]
// },
// {
// _id: ObjectId('000000000000000000000003')
// name: 'Slash',
// connections: []
// }
User.
findOne({ name: 'Axl Rose' }).
populate('connections.item').
exec(function(error, doc) {
// doc.connections[0].item is a User doc
// doc.connections[1].item is an Organization doc
});