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
Mongoose's populate() method does not use MongoDB's $lookup behind the scenes. It simply makes another query to the database. Mongoose does not have functionalities that MongoDB does not have.
Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.
The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.
Mongoose uses two queries to fulfill the request. The a collection is queried to get the docs that match the main query, and then the j collection is queried to populate the d field in the docs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With