DEV Community

Discussion on: How to use Populate in Mongoose & Node.js

Collapse
 
paras594 profile image
Paras 🧙‍♂️ • Edited

There is a concept called "Virtuals". I came across it when I was thinking the same thing. I can only give you hint about it because I have not learned or applied them. In virtuals, you define the conditions for virtuals: 'localField' and 'foreignField'. Local field refers to the name of the field of your current Schema. Foreign field is the name of the field which you are using in other schema to refer to your current Schema. Then you use populate normally.

// modal = Authors
const authorsSchema = {
  name: String,
  article: String 
}

// model = Articles
const articlesSchema = {
  title: String
}

authorsSchema.virtual(
  "yahoo" // can be any name for your virtual, used as key to populate
  {
    ref: "Articles",
    localField: "article", // name of field in author's schema
    foreignField: "title",    
  }
)

const Authors = mongoose.model('Authors', authorsSchema);
const Articles = mongoose.model('Articles', articlesSchema);

// using populate
Authors.find({}).populate("yahoo") // name of virtual

Enter fullscreen mode Exit fullscreen mode

There maybe some mistake in above example but hope it helps you understand the basics atleast.

Maybe once I get time to study, I will write about it as well. :)

Collapse
 
abdulloooh profile image
Abdullah Oladipo

For anyone that wants more info, you can read more here. mongoosejs.com/docs/tutorials/virt...

Thanks @paras594 for the article, really helpful

Thread Thread
 
paras594 profile image
Paras 🧙‍♂️

Welcome and thanks for the reference !! You made the article more useful :)

Collapse
 
shamorasulov profile image
shamorasulov

Thank you for helpfull explaination. You have explained all in easy way and clearly. I wish you good luck!

Thread Thread
 
paras594 profile image
Paras 🧙‍♂️

I am glad you found it helpful. Thank you as well :)
You too Good Luck !!

Collapse
 
khanhle81839451 profile image
Khanh Le

Thanks, that's helpful. But the "yahoo" could be anything, when we call .populate("field name of Authors"). There are something still not clear. However, I get over it by modify data type of _id field.

Thread Thread
 
paras594 profile image
Paras 🧙‍♂️

Good...things are not 100% clear to me as well...but I am sure after trying and testing we can understand it better :)

Thread Thread
 
njugush profile image
Njugush_Dev

Hello paras wanted to know how you can find or filter items based on the populated items

Thread Thread
 
paras594 profile image
Paras 🧙‍♂️

Hi Neural. I don't think, we can find or filter items based on populated items. It may also slow down the query as well.
I would say, go for aggregation, because in aggregation we have better control over how we structure and filter data in different steps. Populate is good for simple to intermediate scenarios but aggregation is more helpful when you need to handle a little complex to advance scenarios