skip to Main Content

I have a following monogodb collections

coll1       coll2
--------     -------
_id          _id
name         coll1_ids

coll2 can have multiple reference to coll1 but coll1 will only have one reference

I want to populate coll2 data in coll1. Is there easier way to do it without using aggregation in Node.js.
Thank you!!!

2

Answers


  1. You can use Mongoose virtual, you need to define virtual in coll1 schema and you can use those virtual in populate like below for example

    coll1Schema.virtual('coll2Data', {
        ref: "coll2",
        localField: "_id",
        foreignField: "coll1_ids"
    });
    

    then you need to pass that virtual name in Mongoose populate function for example

    Coll1.find().populte("coll2Data")
    

    More clarification about mongoose virtual visit this link https://thecodebarbarian.com/mongoose-4.13-virtual-populate-dynamic-refs-fields

    Login or Signup to reply.
  2. for speed, you can also use indexing in MongoDB.

    and if you use Mongoose for MongoDB connection then you can use Populate also

    enter link description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search