MongoDB database connector on NodeJS

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite












What my code does



I am building an Express API server with mongoDB as my database.



I have a list of players which must be added to 2 mongoDB collections (teamList and countryList).



The data schema is similar. My code is as follows.



Data Model model.js



var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var teamSchema = new Schema(
teamid:
type: String,
required: true
,
created:
type: Date
,
lastUpdated:
type: Date,
default: Date.now,
required: true
,
playerList: [
name:
type: String,
required: true,
unique: true
,
dateAdded:
type: Date,
default: Date.now

]
);

module.exports = mongoose.model('teamModel', teamSchema);


var countrySchema = new Schema(
countryid:
type: String,
required: true
,
created:
type: Date
,
lastUpdated:
type: Date,
default: Date.now,
required: true
,
playerList: [
name:
type: String,
required: true,
unique:true
,
dateAdded:
type: Date,
required: true

]
);
module.exports = mongoose.model('countryModel', countrySchema);


Router router.js



module.exports = function(app) 
const teamControllerv1 = require('../v1/controller/teamController');
const countryControllerv1 = require('../v1/controller/countryController');
app.route('/v1/team').post(teamControllerv1.addPlayerToTeam);
app.route('/v1/country').post(countryControllerv1.addPlayerToCountry);
;


Controllers
countryController.js



var mongoose = require('mongoose');
const countryModel = mongoose.model('countryModel');

exports.addPlayerToCountry = function (req, res)
countryModel.update(
countryid: req.body.countryID
,
$addToSet:
countryList:
$each: req.body.playerList


,
upsert: true
,
function (err, data)
if (!err && data)
util.successResponder(res, successText);
else
util.serverErrorResponder(res, errorOccured);

);



teamController.js



var mongoose = require('mongoose');
const TeamModel = mongoose.model('teamModel');

exports.addPlayerToTeam = function (req, res)
teamModel.update(
teamid: req.body.teamID
,
$addToSet:
teamList:
$each: req.body.playerList


,
upsert: true
,
function (err, data)
if (!err && data)
util.successResponder(res, successText);
else
util.serverErrorResponder(res, errorOccured);

);



Problem I am trying to solve



As you can see this code clearly violates DRY. Except the mongoose database connector, everything else in the 2 files is exactly the same. How can I write this in a cleaner way such that the db connector is abstracted away?







share|improve this question

















  • 1




    The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
    – Mast
    Jul 13 at 9:02










  • @Mast Thanks for pointing it out. I agree. I have edited the title to be more descriptive.
    – Sashi
    Jul 13 at 9:06






  • 1




    The site standard is for the title to simply state the task accomplished by the code. Leave the concerns for the question body.
    – Mast
    Jul 13 at 9:15

















up vote
0
down vote

favorite












What my code does



I am building an Express API server with mongoDB as my database.



I have a list of players which must be added to 2 mongoDB collections (teamList and countryList).



The data schema is similar. My code is as follows.



Data Model model.js



var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var teamSchema = new Schema(
teamid:
type: String,
required: true
,
created:
type: Date
,
lastUpdated:
type: Date,
default: Date.now,
required: true
,
playerList: [
name:
type: String,
required: true,
unique: true
,
dateAdded:
type: Date,
default: Date.now

]
);

module.exports = mongoose.model('teamModel', teamSchema);


var countrySchema = new Schema(
countryid:
type: String,
required: true
,
created:
type: Date
,
lastUpdated:
type: Date,
default: Date.now,
required: true
,
playerList: [
name:
type: String,
required: true,
unique:true
,
dateAdded:
type: Date,
required: true

]
);
module.exports = mongoose.model('countryModel', countrySchema);


Router router.js



module.exports = function(app) 
const teamControllerv1 = require('../v1/controller/teamController');
const countryControllerv1 = require('../v1/controller/countryController');
app.route('/v1/team').post(teamControllerv1.addPlayerToTeam);
app.route('/v1/country').post(countryControllerv1.addPlayerToCountry);
;


Controllers
countryController.js



var mongoose = require('mongoose');
const countryModel = mongoose.model('countryModel');

exports.addPlayerToCountry = function (req, res)
countryModel.update(
countryid: req.body.countryID
,
$addToSet:
countryList:
$each: req.body.playerList


,
upsert: true
,
function (err, data)
if (!err && data)
util.successResponder(res, successText);
else
util.serverErrorResponder(res, errorOccured);

);



teamController.js



var mongoose = require('mongoose');
const TeamModel = mongoose.model('teamModel');

exports.addPlayerToTeam = function (req, res)
teamModel.update(
teamid: req.body.teamID
,
$addToSet:
teamList:
$each: req.body.playerList


,
upsert: true
,
function (err, data)
if (!err && data)
util.successResponder(res, successText);
else
util.serverErrorResponder(res, errorOccured);

);



Problem I am trying to solve



As you can see this code clearly violates DRY. Except the mongoose database connector, everything else in the 2 files is exactly the same. How can I write this in a cleaner way such that the db connector is abstracted away?







share|improve this question

















  • 1




    The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
    – Mast
    Jul 13 at 9:02










  • @Mast Thanks for pointing it out. I agree. I have edited the title to be more descriptive.
    – Sashi
    Jul 13 at 9:06






  • 1




    The site standard is for the title to simply state the task accomplished by the code. Leave the concerns for the question body.
    – Mast
    Jul 13 at 9:15













up vote
0
down vote

favorite









up vote
0
down vote

favorite











What my code does



I am building an Express API server with mongoDB as my database.



I have a list of players which must be added to 2 mongoDB collections (teamList and countryList).



The data schema is similar. My code is as follows.



Data Model model.js



var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var teamSchema = new Schema(
teamid:
type: String,
required: true
,
created:
type: Date
,
lastUpdated:
type: Date,
default: Date.now,
required: true
,
playerList: [
name:
type: String,
required: true,
unique: true
,
dateAdded:
type: Date,
default: Date.now

]
);

module.exports = mongoose.model('teamModel', teamSchema);


var countrySchema = new Schema(
countryid:
type: String,
required: true
,
created:
type: Date
,
lastUpdated:
type: Date,
default: Date.now,
required: true
,
playerList: [
name:
type: String,
required: true,
unique:true
,
dateAdded:
type: Date,
required: true

]
);
module.exports = mongoose.model('countryModel', countrySchema);


Router router.js



module.exports = function(app) 
const teamControllerv1 = require('../v1/controller/teamController');
const countryControllerv1 = require('../v1/controller/countryController');
app.route('/v1/team').post(teamControllerv1.addPlayerToTeam);
app.route('/v1/country').post(countryControllerv1.addPlayerToCountry);
;


Controllers
countryController.js



var mongoose = require('mongoose');
const countryModel = mongoose.model('countryModel');

exports.addPlayerToCountry = function (req, res)
countryModel.update(
countryid: req.body.countryID
,
$addToSet:
countryList:
$each: req.body.playerList


,
upsert: true
,
function (err, data)
if (!err && data)
util.successResponder(res, successText);
else
util.serverErrorResponder(res, errorOccured);

);



teamController.js



var mongoose = require('mongoose');
const TeamModel = mongoose.model('teamModel');

exports.addPlayerToTeam = function (req, res)
teamModel.update(
teamid: req.body.teamID
,
$addToSet:
teamList:
$each: req.body.playerList


,
upsert: true
,
function (err, data)
if (!err && data)
util.successResponder(res, successText);
else
util.serverErrorResponder(res, errorOccured);

);



Problem I am trying to solve



As you can see this code clearly violates DRY. Except the mongoose database connector, everything else in the 2 files is exactly the same. How can I write this in a cleaner way such that the db connector is abstracted away?







share|improve this question













What my code does



I am building an Express API server with mongoDB as my database.



I have a list of players which must be added to 2 mongoDB collections (teamList and countryList).



The data schema is similar. My code is as follows.



Data Model model.js



var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var teamSchema = new Schema(
teamid:
type: String,
required: true
,
created:
type: Date
,
lastUpdated:
type: Date,
default: Date.now,
required: true
,
playerList: [
name:
type: String,
required: true,
unique: true
,
dateAdded:
type: Date,
default: Date.now

]
);

module.exports = mongoose.model('teamModel', teamSchema);


var countrySchema = new Schema(
countryid:
type: String,
required: true
,
created:
type: Date
,
lastUpdated:
type: Date,
default: Date.now,
required: true
,
playerList: [
name:
type: String,
required: true,
unique:true
,
dateAdded:
type: Date,
required: true

]
);
module.exports = mongoose.model('countryModel', countrySchema);


Router router.js



module.exports = function(app) 
const teamControllerv1 = require('../v1/controller/teamController');
const countryControllerv1 = require('../v1/controller/countryController');
app.route('/v1/team').post(teamControllerv1.addPlayerToTeam);
app.route('/v1/country').post(countryControllerv1.addPlayerToCountry);
;


Controllers
countryController.js



var mongoose = require('mongoose');
const countryModel = mongoose.model('countryModel');

exports.addPlayerToCountry = function (req, res)
countryModel.update(
countryid: req.body.countryID
,
$addToSet:
countryList:
$each: req.body.playerList


,
upsert: true
,
function (err, data)
if (!err && data)
util.successResponder(res, successText);
else
util.serverErrorResponder(res, errorOccured);

);



teamController.js



var mongoose = require('mongoose');
const TeamModel = mongoose.model('teamModel');

exports.addPlayerToTeam = function (req, res)
teamModel.update(
teamid: req.body.teamID
,
$addToSet:
teamList:
$each: req.body.playerList


,
upsert: true
,
function (err, data)
if (!err && data)
util.successResponder(res, successText);
else
util.serverErrorResponder(res, errorOccured);

);



Problem I am trying to solve



As you can see this code clearly violates DRY. Except the mongoose database connector, everything else in the 2 files is exactly the same. How can I write this in a cleaner way such that the db connector is abstracted away?









share|improve this question












share|improve this question




share|improve this question








edited Jul 13 at 18:02









200_success

123k14143399




123k14143399









asked Jul 13 at 8:24









Sashi

1115




1115







  • 1




    The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
    – Mast
    Jul 13 at 9:02










  • @Mast Thanks for pointing it out. I agree. I have edited the title to be more descriptive.
    – Sashi
    Jul 13 at 9:06






  • 1




    The site standard is for the title to simply state the task accomplished by the code. Leave the concerns for the question body.
    – Mast
    Jul 13 at 9:15













  • 1




    The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
    – Mast
    Jul 13 at 9:02










  • @Mast Thanks for pointing it out. I agree. I have edited the title to be more descriptive.
    – Sashi
    Jul 13 at 9:06






  • 1




    The site standard is for the title to simply state the task accomplished by the code. Leave the concerns for the question body.
    – Mast
    Jul 13 at 9:15








1




1




The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
– Mast
Jul 13 at 9:02




The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly.
– Mast
Jul 13 at 9:02












@Mast Thanks for pointing it out. I agree. I have edited the title to be more descriptive.
– Sashi
Jul 13 at 9:06




@Mast Thanks for pointing it out. I agree. I have edited the title to be more descriptive.
– Sashi
Jul 13 at 9:06




1




1




The site standard is for the title to simply state the task accomplished by the code. Leave the concerns for the question body.
– Mast
Jul 13 at 9:15





The site standard is for the title to simply state the task accomplished by the code. Leave the concerns for the question body.
– Mast
Jul 13 at 9:15











1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










So I kind of figured this out. The db connector can be passed around like just another variable. Silly I didn't realise this before. I created a new file to abstract the model.



dbOperations.js



exports.addToDB = async function (model, dataObj, listName, res) 
model.update(
userid: dataObj.userID
,
$addToSet:
listName:
$each: dataObj.playerID


,
upsert: true
,
function (err, data)
if (!err && data)
util.successResponder(res, successText);
else
util.serverErrorResponder(res, errorOccured);

);
;


teamController.js



var mongoose = require('mongoose');
const teamModel = mongoose.model('teamModel');
const dbOperations = require('../../helper/dbOperations');

exports.addPlayerToTeam = function (req, res)
let dataObj = teamID: req.body.teamID, playerID: req.body.playerList;
dbOperations.addToDB(teamModel,dataObj,'teamList',res);



And similarly for the other file as well. Any other files which follow a similar schema can use it. There is probably a better way to do this so that this can be generalised further to accommodate other schema types.






share|improve this answer





















    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f198410%2fmongodb-database-connector-on-nodejs%23new-answer', 'question_page');

    );

    Post as a guest






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    So I kind of figured this out. The db connector can be passed around like just another variable. Silly I didn't realise this before. I created a new file to abstract the model.



    dbOperations.js



    exports.addToDB = async function (model, dataObj, listName, res) 
    model.update(
    userid: dataObj.userID
    ,
    $addToSet:
    listName:
    $each: dataObj.playerID


    ,
    upsert: true
    ,
    function (err, data)
    if (!err && data)
    util.successResponder(res, successText);
    else
    util.serverErrorResponder(res, errorOccured);

    );
    ;


    teamController.js



    var mongoose = require('mongoose');
    const teamModel = mongoose.model('teamModel');
    const dbOperations = require('../../helper/dbOperations');

    exports.addPlayerToTeam = function (req, res)
    let dataObj = teamID: req.body.teamID, playerID: req.body.playerList;
    dbOperations.addToDB(teamModel,dataObj,'teamList',res);



    And similarly for the other file as well. Any other files which follow a similar schema can use it. There is probably a better way to do this so that this can be generalised further to accommodate other schema types.






    share|improve this answer

























      up vote
      1
      down vote



      accepted










      So I kind of figured this out. The db connector can be passed around like just another variable. Silly I didn't realise this before. I created a new file to abstract the model.



      dbOperations.js



      exports.addToDB = async function (model, dataObj, listName, res) 
      model.update(
      userid: dataObj.userID
      ,
      $addToSet:
      listName:
      $each: dataObj.playerID


      ,
      upsert: true
      ,
      function (err, data)
      if (!err && data)
      util.successResponder(res, successText);
      else
      util.serverErrorResponder(res, errorOccured);

      );
      ;


      teamController.js



      var mongoose = require('mongoose');
      const teamModel = mongoose.model('teamModel');
      const dbOperations = require('../../helper/dbOperations');

      exports.addPlayerToTeam = function (req, res)
      let dataObj = teamID: req.body.teamID, playerID: req.body.playerList;
      dbOperations.addToDB(teamModel,dataObj,'teamList',res);



      And similarly for the other file as well. Any other files which follow a similar schema can use it. There is probably a better way to do this so that this can be generalised further to accommodate other schema types.






      share|improve this answer























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        So I kind of figured this out. The db connector can be passed around like just another variable. Silly I didn't realise this before. I created a new file to abstract the model.



        dbOperations.js



        exports.addToDB = async function (model, dataObj, listName, res) 
        model.update(
        userid: dataObj.userID
        ,
        $addToSet:
        listName:
        $each: dataObj.playerID


        ,
        upsert: true
        ,
        function (err, data)
        if (!err && data)
        util.successResponder(res, successText);
        else
        util.serverErrorResponder(res, errorOccured);

        );
        ;


        teamController.js



        var mongoose = require('mongoose');
        const teamModel = mongoose.model('teamModel');
        const dbOperations = require('../../helper/dbOperations');

        exports.addPlayerToTeam = function (req, res)
        let dataObj = teamID: req.body.teamID, playerID: req.body.playerList;
        dbOperations.addToDB(teamModel,dataObj,'teamList',res);



        And similarly for the other file as well. Any other files which follow a similar schema can use it. There is probably a better way to do this so that this can be generalised further to accommodate other schema types.






        share|improve this answer













        So I kind of figured this out. The db connector can be passed around like just another variable. Silly I didn't realise this before. I created a new file to abstract the model.



        dbOperations.js



        exports.addToDB = async function (model, dataObj, listName, res) 
        model.update(
        userid: dataObj.userID
        ,
        $addToSet:
        listName:
        $each: dataObj.playerID


        ,
        upsert: true
        ,
        function (err, data)
        if (!err && data)
        util.successResponder(res, successText);
        else
        util.serverErrorResponder(res, errorOccured);

        );
        ;


        teamController.js



        var mongoose = require('mongoose');
        const teamModel = mongoose.model('teamModel');
        const dbOperations = require('../../helper/dbOperations');

        exports.addPlayerToTeam = function (req, res)
        let dataObj = teamID: req.body.teamID, playerID: req.body.playerList;
        dbOperations.addToDB(teamModel,dataObj,'teamList',res);



        And similarly for the other file as well. Any other files which follow a similar schema can use it. There is probably a better way to do this so that this can be generalised further to accommodate other schema types.







        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered Jul 13 at 10:25









        Sashi

        1115




        1115






















             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f198410%2fmongodb-database-connector-on-nodejs%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Chat program with C++ and SFML

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            Will my employers contract hold up in court?