簡體   English   中英

ZCCADDEDB567ABAE643E15DCF0974E503Z 架構方法:錯誤 - model 方法不是 function

[英]Mongoose Schema method: Error - model method is not a function

我有兩個 ZCCADCDEDB567ABAE643E15DCF0974E503Z model 模式如下。 LabReport model 包含一組引用的 SoilLab model。 SoilLab model 中有一個 static 方法,我用於 select 檢索 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 數據,當我用更多數據完成 model 時,這將成為一個問題。 我已經深入研究了靜態與方法,並嘗試將其更改為靜態,但它沒有用。

我得到了要填充的土壤實驗室,但不確定為什么此時無法訪問 .SoilToLabJSON 方法。 我是否需要以不同的方式查找()或填充土壤實驗室? 方法不對嗎?

labReport.toLabToJSON 正在傳遞一個數組,這導致了我的錯誤。 我只是將 LabReport.js 編輯為以下內容,以將數組和 map 正確地轉換為 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),

  };
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM