【问题标题】:In mongoose Populate ref to other field instead of _id, reference to custom field not _id在猫鼬中填充引用到其他字段而不是_id,引用自定义字段而不是_id
【发布时间】:2019-03-30 10:05:15
【问题描述】:
    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
  }
}]
}

以上是 3 种模式,即用户、影响者、活动模式。 用于填充的代码如下:

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
    }
]

和预期的结果

[
    {

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

        "__v": 0
    }
]

有人可以告诉 ref 在活动架构中使用影响者字段吗,我想将该字段引用到影响者架构中的 user_id 而不是 _id 字段,我不知道该怎么做。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

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

    .populate("influencers")
    

    使用

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

    但是,这不会完全按照您想要的方式进行。因为它会解析为类似

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

    如果你想要你所说的结果,你需要在之后映射数组。

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 1970-01-01
      • 2012-05-08
      • 2017-09-17
      • 2012-08-26
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      相关资源
      最近更新 更多