无法在Mongoose中填充嵌套的架构引用

时间:2020-04-18 21:31:34

标签: node.js express mongoose backend mongoose-schema

我有多个架构,我正在尝试使用填充查询数据。我正在使用猫鼬(5.9.7)并表达js。

第一个架构-ProfileSchema

const ProfileSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "User"
  },
  jobs: [
    {
      type: Schema.Types.ObjectId,
      ref: "Job"
    }
  ],
  resumes: [
    {
      type: Schema.Types.ObjectId,
      ref: "Resume"
    }
  ],
  name: {
    type: String,
    required: true
  },

});

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

第二个架构-恢复架构

const ResumeSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "User"
  },
  fileLink: { type: String, required: true },
  fileName: { type: String, required: true },
  description: { type: String, required: true }
});

module.exports = Resume = mongoose.model("Resume", ResumeSchema);

路线

router.get(
  "/",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      const profile = await Profile.findOne({
        user: req.user.id
      })
        .populate("resumes")
        .exec();
      res.json(profile);
    } catch (error) {
      return res.status(400).json(error);
    }
  }
);

这将为简历和作业返回一个空数组。我尝试了人口的不同变体,但没有用。尝试过人口稠密。尽管用户可以很好地填充。

编辑:添加简历上传路线

路线

router.post(
  "/upload",
  passport.authenticate("jwt", { session: false }),
  upload.single("resume"),
  async (req, res) => {
    try {
    // upload to s3 code here

      if (data) {
        const resumeData = {
          description: req.body.description,
          fileName: params.Key,
          fileLink: data.Location,
          user: req.user.id
        };

        const resume = new Resume(resumeData);
        const fileSavedToSchema = await resume.save();
        return res.json(fileSavedToSchema);
      }
    } catch (error) {
      console.log(error);
    }
  }
);

我可以使用其他途径查看简历。

0 个答案:

没有答案