hhs
hhs

Reputation: 714

mongoose populate field without ref option

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

Answers (2)

Faiz Ahmed
Faiz Ahmed

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

aaronheckmann
aaronheckmann

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

Related Questions