填充嵌套的 ObjectId

Populate nested ObjectId

我的个人资料文档保存在我的数据库中如下:

{
    "_id": {
        "$oid": "5c3aa1de18ad682fb1444138"
    },
    "user": {
        "$oid": "5c318f56e3224b15e0fdbd06"
    },
    "company": {
        "info": {
            "$oid": "5c318f56e3224b15e0fdbd07"
        },
        "position": "Stemuli"
    },
    "hometown": "Dallas",
    "date": {
        "$date": "2019-01-13T02:26:38.185Z"
    },
    "__v": 0
}

我正在尝试填充新保存的配置文件中的字段 company.info

new Profile(profileFields).save().then(profile => {
          Profile.populate(profile, { path: "company.info" }, (err, p) => {
            console.log(err);
            console.log(p);
          });
        });

我得到公司字段的以下返回

company: {id: "5c318f56e3224b15e0fdbd07", position: "Stemuli"}

这个id链接到的文档如下:

{
    "_id": {
        "$oid": "5c318f56e3224b15e0fdbd07"
    },
    "employees": [
        {
            "$oid": "5c318f56e3224b15e0fdbd06"
        }
    ],
    "name": "Company",
    "__v": 14
}

我怎样才能让它填充实际的公司文档而不仅仅是 ID?

配置文件架构

// Create Schema
const ProfileSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "users"
  },
  company: {
    id: { type: Schema.Types.ObjectId, ref: "industrypartners" },
    position: { type: String }
  },
  work_experience: Array,
  hometown: { type: String },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = Profile = mongoose.model("profile", ProfileSchema);

行业合作伙伴架构

// Create Schema
const IndustryPartnerSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  schools: [{ type: Schema.Types.ObjectId, ref: "schools" }]
});

module.exports = IndustryPartner = mongoose.model(
  "industrypartner",
  IndustryPartnerSchema
);

试试这个:

new Profile(profileFields).save().then(profile => {
  Profile.populate(Profile, { 
    path: "company.info",
    select: {
      _id: 1,
      employees: 1,
      name: 1,
    }
  }, (err, p) => {
    console.log(err);
    console.log(p);
  });
});