Reputation: 714
I have 3 schema:
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"});
and
var ConversationSchema = new Schema( {
participants: [{user:{type: ObjectId, required: true}],
creator: {type: ObjectId, required: true},
status: { type:Number, required: true, default:1 }
}, { collection:"conversation" } );
In ConversationSchema I have creator field whic has now ref option, because it can be type of User1Schema or User2Schema.
How can I populate creator field using mongoose
Upvotes: 22
Views: 15382
Reputation: 11
As of 27th March 2019 the way to do so is:
1) Setting the field you want to populate as a ObjectId without providing a ref.
var eventSchema = new Schema({
name: String,
// The id of the corresponding conversation
// Notice there's no ref here!
conversation: ObjectId
});
2) While making the query pass the model for the schema along with the query:
Event.
find().
populate({ path: 'conversation', model: Conversation }).
exec(function(error, docs) { /* ... */ });
REF: https://mongoosejs.com/docs/populate.html#cross-db-populate
Upvotes: 1
Reputation: 10780
Conversation.find().populate('creator', null, 'User2').exec(callback)
The docs aren't clear. Will update soon.
Also, the syntax for this will be simpler in v3.6.
Upvotes: 26