Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose populate field without ref option

Tags:

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

like image 504
hhs Avatar asked Jan 31 '13 14:01

hhs


People also ask

Does Mongoose populate use lookup?

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.

How does populate work in Mongoose?

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.

What does REF do in Mongoose?

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.

How does Mongoose populate work under the hood?

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.


1 Answers

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.

like image 116
aaronheckmann Avatar answered Oct 20 '22 19:10

aaronheckmann