【问题标题】:Do I have to define different mongodb models in separate files?我是否必须在单独的文件中定义不同的 mongodb 模型?
【发布时间】:2019-11-05 10:54:24
【问题描述】:

最近,我一直在使用 mongodb 和一个模型。当我尝试添加第二个模型时,我注意到我可能会遇到一些问题。 首先,这是一个单一模型的代码:

riskRating.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let riskRatingRow = new Schema({
  securitycause: {
    type: String
  },
  operationalrisk: {
    type: String
  },
  riskid: {
    type: String
  },
  riskstatements: {
    type: String
  },
  businessline: {
    type: String
  },
  supportingasset: {
    type: String
  },
  category: {
    type: String
  },
  frequency: {
    type: String
  },
  impact: {
    type: String
  },
  inherentriskrating: {
    type: String 
  },
  controleffectiveness: {
    type: String
  },
  residualrisk: {
    type: String
  }
});
module.exports = mongoose.model('riskRating', riskRatingRow);

这是我在服务器代码中使用它的方式:

server.js

   const RiskRatingRow= require('./models/riskRating');
    router.route('/table').get((req, res) => {
        RiskRatingRow.find((err, tableData) => {
            if (err)
                console.log(err);
            else
                res.json(tableData);
        });
    });

router.route('/table/add').post((req, res) => {
    console.log('REQ.body is ', req.body);
    const riskRatingRow = new RiskRatingRow(req.body);
    riskRatingRow.save()
        .then(issue => {
            res.status(200).json({
                'tableRow': 'Added successfully'
            });
        })
        .catch(err => {
            res.status(400).send('Failed to create new record');
        });
});

第一个问题:到目前为止有什么问题吗?
现在,当我添加第二个模型时:

twoModels.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let riskRatingRow = new Schema({
    //1st model defintion
});
const businessLineDashboardRow = new Schema({
    //2nd model defintion
});
module.exports = mongoose.model('businessLineDashboard', businessLineDashboardRow);
module.exports = mongoose.model('riskRating', riskRatingRow);

我注意到在 server.js 中,当我使用第一个模型时,我没有直接引用它。我宁愿引用 singleModel.js 文件。尤其是这两行:

   const RiskRatingRow = require('./models/riskRating');
   // Here I am using directly the file reference RiskRatingRow 
   const riskRatingRow = new RiskRatingRow(req.body);
   // Same thing here
        RiskRatingRow.find((err, tableData) => {
            if (err)
                console.log(err);
            else
                res.json(tableData);
        });

所以,当我准备使用第二个模型时,我发现自己被卡住了,因为正如我在使用第一个模型时所解释的那样,我没有直接引用它。我刚刚引用了该文件。
问题是,这实际上工作正常。
但是,我不知道模型文件是否包含两个模型,我应该如何在服务器文件中使用它们。
所以这是我的另外两个问题:
1/ 即使我只是引用模型定义文件,代码怎么会起作用?
2/ 我应该在单独的文件中定义第二个模型,并引用它以便能够使用它吗?
谢谢,我希望我足够清楚。

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    module.exports 可以是包含多个事物作为属性的对象:

    module.exports = {
      RiskRatingRow: mongoose.model('businessLineDashboard', businessLineDashboardRow),
      BusinessLineDashboardRow: mongoose.model('riskRating', riskRatingRow),
    }
    

    由于默认情况下它是一个空对象 ({}),您也可以单独分配导出:

    module.exports.RiskRatingRow = mongoose.model('businessLineDashboard', businessLineDashboardRow)
    module.exports.BusinessLineDashboardRow = mongoose.model('riskRating', riskRatingRow)
    

    您现在可以将destructure 的模型从server.js 里面的对象中取出来:

    const { RiskRatingRow, BusinessLineDashboardRow } = require('./models/twoModels')
    

    或者,如果你想用老式的方式来做:

    const models = require('./models/twoModels')
    const RiskRatingRow = models.RiskRatingRow
    const BusinessLineDashboardRow = models.BusinessLineDashboardRow
    

    【讨论】:

      【解决方案2】:

      Niklas 的回答很中肯。不过,我找到了一个更完整的解决方案:

      riskRating.js

      const mongoose = require('mongoose')
      const Schema = mongoose.Schema;
      module.exports = function(mongoose) {
        let riskRatingRow = new Schema({
          securitycause: {
            type: String
          },
          operationalrisk: {
            type: String
          },
          riskid: {
            type: String
          },
          riskstatements: {
            type: String
          },
          businessline: {
            type: String
          },
          supportingasset: {
            type: String
          },
          category: {
            type: String
          },
          frequency: {
            type: String
          },
          impact: {
            type: String
          },
          inherentriskrating: {
            type: String 
          },
          controleffectiveness: {
            type: String
          },
          residualrisk: {
            type: String
          }
        });
        let businessLineDashboardRow = new Schema({
          ref: {
            type: String
          },
          riskstatements: {
            type: String
          },
          maximpact: {
            type: String
          },
          controleffectiveness: {
            type: String
          },
          recommendedriskrating: {
            type: String
          },
          frequency: {
            type: String
          },
          impact: {
            type: String
          },
          validatedreviewriskrating: {
            type: String
          },
          rationalforriskadjustment: {
            type: String
          }
        });
      
        var models = {
          BusinessLineDashboard : mongoose.model('BusinessLineDashboard', businessLineDashboardRow),
          RiskRating : mongoose.model('RiskRating', riskRatingRow)
        };
        return models;
      }
      

      server.js

      router.route('/riskRating2').get((req, res) => {
          models.RiskRating.find((err, tableData) => {
              if (err)
                  console.log(err);
              else
                  res.json(tableData);
                  analyseDeRisqueService.determineMaxImpactForEachRisk(tableData)
      
          });
      });
      

      【讨论】:

      • 我不明白你为什么要导出一个以moongoose 作为参数的函数(或者根本就没有函数)。这将需要使用require('./models/twoModels')(require('mongoose')) 导入模型,这没有多大意义,因为mongoose 甚至不是一个实例。
      • 你是对的。我在这里找到了:stackoverflow.com/questions/9960486/…
      猜你喜欢
      • 2012-11-18
      • 2023-01-30
      • 2015-05-13
      • 2013-03-04
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      相关资源
      最近更新 更多