Node.js 在mongoose中,将引用填充到其他字段而不是_id,对自定义字段而不是_id的引用

Node.js 在mongoose中,将引用填充到其他字段而不是_id,对自定义字段而不是_id的引用,node.js,mongodb,mongoose,mongoose-populate,Node.js,Mongodb,Mongoose,Mongoose Populate,以上是3种模式,即用户、影响者、活动模式。 用于填充的代码如下所示: userSchema={ username: { type: String, required: true, unique: true }, password: { type: String, required: true }, role: { type: String } } influencerSchema={ user_id: { ty

以上是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
  }
}]
}
上述函数给出的结果是

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);
      }
    });
  });
}
以及预期的结果

[
    {

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

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

        "__v": 0
    }
]

是否有人告诉ref使用活动模式中的“影响者”字段,我想将该字段引用到“影响者”模式中的“用户id”,而不是“id”字段。我不知道如何操作。

您使用的填充错误。实际上,您不想填充影响者,但如果我理解正确,则影响者ID。而不是

[
    {

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

        "__v": 0
    }
]
使用

然而,这并不是你想要的结果。因为它会解决类似的问题

.populate({path: "influencers.influencerId"})
如果您希望按照您所说的那样得到结果,则需要在之后映射数组

.populate({path: "influencers.influencerId"})
"influencers" : [
    "status" : 0,
    "influencerId" : {
        //content of influencer
    }
]