0

Recently, I have been working with mongodb with one single model. When I tried to add a second model, I noticed that I might face some issues. First, here's the code with one single model:

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);

Here's how I use it in the server code:

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');
        });
});

First question: Is there anything wrong so far?
Now, when I add the second model:

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);

I have noticed that in server.js, when I am using the first model, I am not referencing it directly. I'm rather referecing the singleModel.js file. Particularly in these two lines:

   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);
        });

So, when I was about to make use of the second model, I found myself blocked since as I explained when I used the first model, I didn't reference it directly. I just referenced the file.
Thing is, that actually works fine.
But, I don't know if the model file contains two models, how am I supposed to make use of them both in the server file.
So here's my two other questions:
1/ How come that code works even though I am just referecing the model defintion file?
2/ Should I define the second model in a separate file, and reference it in order to be able to use it?
Thank you, I hope I was clear enough.

Ahmed Ghrib
  • 695
  • 4
  • 13
  • 29

2 Answers2

1

module.exports can be an object containing multiple things as properties:

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

Since it's an empty object ({}) by default you can also assign the exports individually:

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

You can now destructure the models out of the object inside server.js:

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

Or, if you want to do it the old-school way:

const models = require('./models/twoModels')
const RiskRatingRow = models.RiskRatingRow
const BusinessLineDashboardRow = models.BusinessLineDashboardRow
Niklas Higi
  • 2,188
  • 1
  • 14
  • 30
0

Niklas's answer is on point. However, I have found a more complete solution:

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)

    });
});
Ahmed Ghrib
  • 695
  • 4
  • 13
  • 29
  • I don't understand why you're exporting a function that takes `moongoose` as an argument (or a function at all for that matter). This would require importing the models using `require('./models/twoModels')(require('mongoose'))` which doesn't make a whole lot of sense since `mongoose` is not even an instance. – Niklas Higi Jun 23 '19 at 10:57
  • You're right. I found that here :https://stackoverflow.com/questions/9960486/defining-mongoose-models-in-separate-module – Ahmed Ghrib Jun 23 '19 at 11:21