3
    userSchema={
  username: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  role: {
    type: String
  }
}

influencerSchema={
user_id: {
  type: Schema.Types.ObjectId,
  ref: 'users'
},
profile: {
  firstname: {
    type: String
  },
  lastname: {
    type: String,
    default: null
  },
  mob: {
    type: String,
    default: null
  },
  email: {
    type: String,
    default: null
  },
  dob: {
    type: Date,
    default: null
  },
  gender: {
    type: String,
    default: null
  }
  }
}


campaign_schema={
CampaignName: {
  type: String,
  required: true
},
Brandcreated: {
  type: Schema.Types.ObjectId,
  required: true
},
status: {
  type: Number,
  default: 0
},
influencers: [{
  influencerId: {
    type: Schema.Types.ObjectId,
    ref:"influencer"
    },
  status: {
    type: Number,
    default: 0
  }
}]
}

The above are 3 schema i.e User , influencer, Campaign schema. Code use for populate is give below:

function(body) {

  return new Promise(function(resolve, reject) {
campaign.find({
      "_id": body.campaignId
    }).populate('influencer')
    .exec(function(err, doc) {
      console.log(err);
      if (err) {
        reject();
      } else {
        resolve(doc);
      }
    });
  });
}

the result given by above function is

[
    {

        "status": 0,
        "_id": "5bc4a9bf0c67a642d74ab6d1",
        "influencers": [
            {
                "status": 0,
                "_id": "5bccc0052db612466d8f26fb",
                "influencerId": "5bbef7cd8c43aa1c4e9a09b5"

            }
        ],
        "CampaignName": "testCampaign",
        "Brandcreated": "5bbf7857a7a55d30426cde37",

        "__v": 0
    }
]

and the result expecting

[
    {

        "status": 0,
        "_id": "5bc4a9bf0c67a642d74ab6d1",
        "influencers": [
            {
                "status": 0,
                "_id": "5bccc0052db612466d8f26fb",
                "influencerId": "5bbef7cd8c43aa1c4e9a09b5"
                user_id: {}
                profile:{}
            }
        ],
        "CampaignName": "testCampaign",
        "Brandcreated": "5bbf7857a7a55d30426cde37",

        "__v": 0
    }
]

Can someone told ref use influencers field in campaign schema ,i want to refer that field to user_id in influencer Schema instead of_id field i dont how to do it.

1 Answers1

0

You are using the populate wrong. You actually dont want to populate influencer, but InfluencerId if I understand correctly. Instead of

.populate("influencers")

use

.populate({path: "influencers.influencerId"})

However that will not exacltly turn out the way you want to. as it will resolve to something like

"influencers" : [
    "status" : 0,
    "influencerId" : {
        //content of influencer
    }
]

If you want your the result as you stated you need to map the array afterwards.

relief.melone
  • 3,042
  • 1
  • 28
  • 57