猫鼬模式方法:错误-模型方法不是函数

时间:2020-07-31 19:45:17

标签: javascript node.js mongodb express mongoose

我有两个Mongoose模型架构,如下所示。 LabReport模型包含参考的SoilLab模型的数组。我正在使用SoilLab模型中的静态方法来选择检索LabReport时要显示的字段。

//LabReport.js
var mongoose = require("mongoose");
var SoilLab = mongoose.model("SoilLab");

var LabReportSchema = new mongoose.Schema(
  {
    labFarm: { type: mongoose.Schema.Types.ObjectId, ref: "Farm" },
    testName: { type: String },
    soilLabs: [{ type: mongoose.Schema.Types.ObjectId, ref: "SoilLab" }],
  },
  { timestamps: true, usePushEach: true }
);

LabReportSchema.methods.toLabToJSON = function () {
  return {
    labReport_id: this._id,
    testName: this.testName,
    soilLabs: this.soilLabs.SoilToLabJSON(),

  };
};

mongoose.model("LabReport", LabReportSchema);
//SoilLab.js
var mongoose = require("mongoose");

var SoilLabSchema = new mongoose.Schema(
  {
    description: { type: String },
    sampleDate: { type: Date },
    source: { type: String },
  },
  { timestamps: true, usePushEach: true }
);

SoilLabSchema.methods.SoilToLabJSON = function () {
  return {
    description: this.description,
    sampleDate: this.sampleDate,
    source: this.source,
  };
};

mongoose.model("SoilLab", SoilLabSchema);

当我尝试检索LabReport时,出现“ this.soilLabs.SoilToLabJSON不是函数”。这就是我试图检索LabReport的方式。

//labReports.js

...

    return Promise.all([
        LabReport.find()
          .populate("soilLabs")
          .exec(),
        LabReport.count(query).exec(),
        req.payload ? User.findById(req.payload.id) : null,
      ]).then(function (results) {
        var labReports = results[0];
        var labReportsCount = results[1];
        var user = results[2];
        return res.json({
          labReports: labReports.map(function (labReport) {
            return labReport.toLabToJSON(user);   //This cant find SoilToLabJSON 
          }),

如果我在LabReport.js中删除.SoilToLabJSON并仅调用this.soilLabs,它会起作用,但是会输出所有的SoilLabs数据,当我用更多数据完成模型时,这将成为问题。我已经稍微研究了statics和方法,并尝试将其更改为statics,但是没有用。

我让soilLabs填充,但不确定为什么此时无法访问.SoilToLabJSON方法。我是否需要find()或以其他方式填充SoilLab?方法不正确吗?

1 个答案:

答案 0 :(得分:1)

labReport.toLabToJSON正在传递一个数组,这对我造成了错误。我只是将LabReport.js编辑为以下内容,以获取数组并将其正确映射到SoilToLabJSON。

myTestSoilLabOutput = function (soilLabs) {
  var test = soilLabs.map(function (soilLab) {
    return soilLab.SoilToLabJSON();
  });
  return test;

将LabReportSchema.methods.toLabToJSON更改为:

LabReportSchema.methods.toLabToJSON = function () {
  return {
    labReport_id: this._id,
    testName: this.testName,
    soilLabs: myTestSoilLabOutput(this.soilLabs),

  };
};