试图查找时猫鼬字段未正确填充

时间:2020-04-11 17:17:29

标签: javascript mongodb typescript mongoose nestjs

我正在尝试使用NESTJS和MONGOOSE获取具有相关报告的公司列表。

代码如下:

公司架构

export const CompanySchema = new Schema({
  name: String,
  description: String,
  address: String,
  email: String,
  reports: { type: Schema.Types.ObjectId, ref: "Report" },
  createdAt: { type: Date, default: Date.now }
});

CompanySchema.virtual("company", {
  ref: "Report",
  localField: "_id",
  foreignField: "company"
});

报告架构

export const ReportSchema = new Schema({
  company: { type: Schema.Types.ObjectId, ref: "Company" },
  name: String,
  period: String,
  assignee: String,
  type: {
    type: String,
    enum: ["Periodic", "Annual", "Financial", "Analytical"]
  },
  submitted: { type: Date, default: Date.now }
});

在参考键 company 下可以很好地填充ID 现在,我正在尝试查找具有相关报告的公司列表。

公司服务文件

  async getAllCompanies(): Promise<Company[]> {
    const companies = await this.companyModel
      .find()
      .populate({
        path: "reports"
      })
      .exec();
    // .select("-__v -_id -createdAt");
    return companies;
  }

公司控制文件

@Get("companies")
  @ApiResponse({ status: 200 })
  async getAllCompanies(@Res() res) {
    try {
      const companies = await this.companyService.getAllCompanies();
      return res.status(HttpStatus.OK).json({ status: 200, data: companies });
    } catch (error) {
      console.log(error);
      return res
        .status(HttpStatus.INTERNAL_SERVER_ERROR)
        .json({ status: 500, error: "An error occurred." });
    }

}

我用来在公司字段中填充报告的代码

报告服务文件

@Injectable()
export class ReportService {
  constructor(
    @InjectModel("Report")
    private reportModel: Model<Report>
  ) {}
  async addReport(
    createReportDTO: CreateReportDTO,
    companyId: string
  ): Promise<Report> {
    const newReport = await this.reportModel({
      ...createReportDTO,
      company: companyId
    });
    await newReport.save();
    return newReport.populate("company");
  }

它不填充报告,仅列出公司列表,我缺少什么吗?请帮忙。谢谢。

0 个答案:

没有答案