我有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" } );
在ConversationSchema中我有创建者字段whic现在有ref选项,因为它可以是User1Schema或User2Schema的类型。
如何使用mongoose填充创建者字段
答案 0 :(得分:23)
Conversation.find().populate('creator', null, 'User2').exec(callback)
docs尚不清楚。将很快更新。
此外,在v3.6中,此语法将更简单。
答案 1 :(得分:0)
截至2019年3月27日,方法是:
1)将要填充的字段设置为不提供的对象ID。
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) { /* ... */ });
REF:https://mongoosejs.com/docs/populate.html#cross-db-populate