22

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

hhs
  • 716
  • 1
  • 6
  • 22
  • 2
    See the `mongoose-dbref` plugin: https://github.com/goulash1971/mongoose-dbref – JohnnyHK Jan 31 '13 at 15:15
  • Here's a more up-to-date branch of `mongoose-dbref` https://github.com/apiaryio/mongoose-dbref. However, if at all possible, you should try to just change your schema instead of branching it: http://stackoverflow.com/questions/7617002/dealing-with-schema-changes-in-mongoose – mjhm Jan 31 '13 at 16:43

2 Answers2

26
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.

aaronheckmann
  • 10,625
  • 2
  • 40
  • 30
1

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

Faiz Ahmed
  • 11
  • 1