我有 3 个模式:
var User1Schema = new Schema({
name: {type:String , trim: true, required: true },
status: {type:Number, required: true, default:1}
},{collection:"user_1"});
,
var User2Schema = new Schema({
name: {type:String , trim: true, required: true },
email: {type: String, required: true, index: {unique: true} },
status: {type:Number, required: true, default:1}
},{collection:"user_2"});
和
var ConversationSchema = new Schema( {
participants: [{user:{type: ObjectId, required: true}],
creator: {type: ObjectId, required: true},
status: { type:Number, required: true, default:1 }
}, { collection:"conversation" } );
在对话模式中,我有创建者字段,现在有 ref 选项,因为它可以是用户 1 架构或用户 2 模式的类型。
如何使用猫鼬填充创建者字段
Conversation.find().populate('creator', null, 'User2').exec(callback)
文档不清楚。将很快更新。
此外,在 v3.6 中,这样做的语法会更简单。
截至 2019 年 3 月 27 日,这样做的方法是:
1) 将要填充的字段设置为 ObjectId,而不提供引用。
var eventSchema = new Schema({
name: String,
// The id of the corresponding conversation
// Notice there's no ref here!
conversation: ObjectId
});
2) 在使查询传递架构的模型以及查询时:
Event.
find().
populate({ path: 'conversation', model: Conversation }).
exec(function(error, docs) { /* ... */ });
参考: https://mongoosejs.com/docs/populate.html#cross-db-populate