adding functions to a knex/bookshelf model in node/express











up vote
0
down vote

favorite












I have a model like this:



const User = db.Model.extend({
tableName: 'users',
hasSecurePassword: true
});

module.exports = User;


With this I can do things like



const User      = require("../models/user");

User.fetchAll({columns:['id','email']}).then((data) => {
res.json(data);
}).catch(err => {
res.json(err);
});


What if I want to add costume functions to my model such as:



var connection  = require('./dbconnection.js');
var User = db.Model.extend({
tableName: 'users',
hasSecurePassword: true
});


User.getUsers = (callback) => {
if (connection) {
const newLocal = "select * FROM users";
connection.query(newLocal, (err,rows,fields) => {
if (err) {
return res.sendStatus(500);
} else {
callback(null,rows);
}
});
}
};

module.exports = User;


And then do something like:



 const User      = require("../models/user");
User.getUsers((err,data) => {
res.status(200).json(data);
});


Is this posible? Or should I just conform with the bookshelf functions?
Right now the error I get is connection.query is not a function



And models/dbconnection.js is:



const mysql = require('mysql');
port = process.env.PORT || 3333;


if (port == 3333) {
var connection = mysql.createConnection({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
insecureAuth: true
});
} else {
console.log("Error");
}

connection.connect();
module.exports.connection = connection;









share|improve this question









New contributor




daniel gon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    up vote
    0
    down vote

    favorite












    I have a model like this:



    const User = db.Model.extend({
    tableName: 'users',
    hasSecurePassword: true
    });

    module.exports = User;


    With this I can do things like



    const User      = require("../models/user");

    User.fetchAll({columns:['id','email']}).then((data) => {
    res.json(data);
    }).catch(err => {
    res.json(err);
    });


    What if I want to add costume functions to my model such as:



    var connection  = require('./dbconnection.js');
    var User = db.Model.extend({
    tableName: 'users',
    hasSecurePassword: true
    });


    User.getUsers = (callback) => {
    if (connection) {
    const newLocal = "select * FROM users";
    connection.query(newLocal, (err,rows,fields) => {
    if (err) {
    return res.sendStatus(500);
    } else {
    callback(null,rows);
    }
    });
    }
    };

    module.exports = User;


    And then do something like:



     const User      = require("../models/user");
    User.getUsers((err,data) => {
    res.status(200).json(data);
    });


    Is this posible? Or should I just conform with the bookshelf functions?
    Right now the error I get is connection.query is not a function



    And models/dbconnection.js is:



    const mysql = require('mysql');
    port = process.env.PORT || 3333;


    if (port == 3333) {
    var connection = mysql.createConnection({
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    insecureAuth: true
    });
    } else {
    console.log("Error");
    }

    connection.connect();
    module.exports.connection = connection;









    share|improve this question









    New contributor




    daniel gon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have a model like this:



      const User = db.Model.extend({
      tableName: 'users',
      hasSecurePassword: true
      });

      module.exports = User;


      With this I can do things like



      const User      = require("../models/user");

      User.fetchAll({columns:['id','email']}).then((data) => {
      res.json(data);
      }).catch(err => {
      res.json(err);
      });


      What if I want to add costume functions to my model such as:



      var connection  = require('./dbconnection.js');
      var User = db.Model.extend({
      tableName: 'users',
      hasSecurePassword: true
      });


      User.getUsers = (callback) => {
      if (connection) {
      const newLocal = "select * FROM users";
      connection.query(newLocal, (err,rows,fields) => {
      if (err) {
      return res.sendStatus(500);
      } else {
      callback(null,rows);
      }
      });
      }
      };

      module.exports = User;


      And then do something like:



       const User      = require("../models/user");
      User.getUsers((err,data) => {
      res.status(200).json(data);
      });


      Is this posible? Or should I just conform with the bookshelf functions?
      Right now the error I get is connection.query is not a function



      And models/dbconnection.js is:



      const mysql = require('mysql');
      port = process.env.PORT || 3333;


      if (port == 3333) {
      var connection = mysql.createConnection({
      host: process.env.DB_HOST,
      port: process.env.DB_PORT,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      insecureAuth: true
      });
      } else {
      console.log("Error");
      }

      connection.connect();
      module.exports.connection = connection;









      share|improve this question









      New contributor




      daniel gon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I have a model like this:



      const User = db.Model.extend({
      tableName: 'users',
      hasSecurePassword: true
      });

      module.exports = User;


      With this I can do things like



      const User      = require("../models/user");

      User.fetchAll({columns:['id','email']}).then((data) => {
      res.json(data);
      }).catch(err => {
      res.json(err);
      });


      What if I want to add costume functions to my model such as:



      var connection  = require('./dbconnection.js');
      var User = db.Model.extend({
      tableName: 'users',
      hasSecurePassword: true
      });


      User.getUsers = (callback) => {
      if (connection) {
      const newLocal = "select * FROM users";
      connection.query(newLocal, (err,rows,fields) => {
      if (err) {
      return res.sendStatus(500);
      } else {
      callback(null,rows);
      }
      });
      }
      };

      module.exports = User;


      And then do something like:



       const User      = require("../models/user");
      User.getUsers((err,data) => {
      res.status(200).json(data);
      });


      Is this posible? Or should I just conform with the bookshelf functions?
      Right now the error I get is connection.query is not a function



      And models/dbconnection.js is:



      const mysql = require('mysql');
      port = process.env.PORT || 3333;


      if (port == 3333) {
      var connection = mysql.createConnection({
      host: process.env.DB_HOST,
      port: process.env.DB_PORT,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      insecureAuth: true
      });
      } else {
      console.log("Error");
      }

      connection.connect();
      module.exports.connection = connection;






      node.js express knex.js bookshelf.js






      share|improve this question









      New contributor




      daniel gon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      daniel gon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited Nov 5 at 18:00





















      New contributor




      daniel gon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked Nov 5 at 17:46









      daniel gon

      264




      264




      New contributor




      daniel gon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      daniel gon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      daniel gon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          Yes, you can add your custom functions to bookshelf models in two different ways.




          1. Instance methods


          For example, you want to return user's full name, your User model will look something like this



          const User = db.Model.extend({
          tableName: 'users',
          hasSecurePassword: true,

          //be careful here, if you use arrow function `this` context will change
          //and your function won't work as expected

          returnFullName: function() {
          return this.get('firstname') + this.get('lastname');
          }
          });

          module.exports = User;


          then you will call this function like this



          User.forge().where({id: SOME_ID}).fetch()
          .then(function(user) {
          var fullName = user.returnFullName();
          });



          1. Class methods


          For example, you want to return user's email based on username, your User model will look something like this



          const User = db.Model.extend({
          tableName: 'users',
          hasSecurePassword: true
          }, {

          getUserEmail: function(SOME_USERNAME) {
          return User.forge().where({username: SOME_USERNAME}).fetch()
          .then(function (user) {
          if(user) {
          return Promise.resolve(user.get('email'));
          } else {
          return Promise.resolve(null);
          }
          });
          }
          });

          module.exports = User;


          then you can call this function like



          User.getUserEmail(SOME_USERNAME)
          .then(function(email) {
          console.log(email);
          });





          share|improve this answer





















            Your Answer






            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: "1"
            };
            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: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });






            daniel gon is a new contributor. Be nice, and check out our Code of Conduct.










             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53159554%2fadding-functions-to-a-knex-bookshelf-model-in-node-express%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
            0
            down vote



            accepted










            Yes, you can add your custom functions to bookshelf models in two different ways.




            1. Instance methods


            For example, you want to return user's full name, your User model will look something like this



            const User = db.Model.extend({
            tableName: 'users',
            hasSecurePassword: true,

            //be careful here, if you use arrow function `this` context will change
            //and your function won't work as expected

            returnFullName: function() {
            return this.get('firstname') + this.get('lastname');
            }
            });

            module.exports = User;


            then you will call this function like this



            User.forge().where({id: SOME_ID}).fetch()
            .then(function(user) {
            var fullName = user.returnFullName();
            });



            1. Class methods


            For example, you want to return user's email based on username, your User model will look something like this



            const User = db.Model.extend({
            tableName: 'users',
            hasSecurePassword: true
            }, {

            getUserEmail: function(SOME_USERNAME) {
            return User.forge().where({username: SOME_USERNAME}).fetch()
            .then(function (user) {
            if(user) {
            return Promise.resolve(user.get('email'));
            } else {
            return Promise.resolve(null);
            }
            });
            }
            });

            module.exports = User;


            then you can call this function like



            User.getUserEmail(SOME_USERNAME)
            .then(function(email) {
            console.log(email);
            });





            share|improve this answer

























              up vote
              0
              down vote



              accepted










              Yes, you can add your custom functions to bookshelf models in two different ways.




              1. Instance methods


              For example, you want to return user's full name, your User model will look something like this



              const User = db.Model.extend({
              tableName: 'users',
              hasSecurePassword: true,

              //be careful here, if you use arrow function `this` context will change
              //and your function won't work as expected

              returnFullName: function() {
              return this.get('firstname') + this.get('lastname');
              }
              });

              module.exports = User;


              then you will call this function like this



              User.forge().where({id: SOME_ID}).fetch()
              .then(function(user) {
              var fullName = user.returnFullName();
              });



              1. Class methods


              For example, you want to return user's email based on username, your User model will look something like this



              const User = db.Model.extend({
              tableName: 'users',
              hasSecurePassword: true
              }, {

              getUserEmail: function(SOME_USERNAME) {
              return User.forge().where({username: SOME_USERNAME}).fetch()
              .then(function (user) {
              if(user) {
              return Promise.resolve(user.get('email'));
              } else {
              return Promise.resolve(null);
              }
              });
              }
              });

              module.exports = User;


              then you can call this function like



              User.getUserEmail(SOME_USERNAME)
              .then(function(email) {
              console.log(email);
              });





              share|improve this answer























                up vote
                0
                down vote



                accepted







                up vote
                0
                down vote



                accepted






                Yes, you can add your custom functions to bookshelf models in two different ways.




                1. Instance methods


                For example, you want to return user's full name, your User model will look something like this



                const User = db.Model.extend({
                tableName: 'users',
                hasSecurePassword: true,

                //be careful here, if you use arrow function `this` context will change
                //and your function won't work as expected

                returnFullName: function() {
                return this.get('firstname') + this.get('lastname');
                }
                });

                module.exports = User;


                then you will call this function like this



                User.forge().where({id: SOME_ID}).fetch()
                .then(function(user) {
                var fullName = user.returnFullName();
                });



                1. Class methods


                For example, you want to return user's email based on username, your User model will look something like this



                const User = db.Model.extend({
                tableName: 'users',
                hasSecurePassword: true
                }, {

                getUserEmail: function(SOME_USERNAME) {
                return User.forge().where({username: SOME_USERNAME}).fetch()
                .then(function (user) {
                if(user) {
                return Promise.resolve(user.get('email'));
                } else {
                return Promise.resolve(null);
                }
                });
                }
                });

                module.exports = User;


                then you can call this function like



                User.getUserEmail(SOME_USERNAME)
                .then(function(email) {
                console.log(email);
                });





                share|improve this answer












                Yes, you can add your custom functions to bookshelf models in two different ways.




                1. Instance methods


                For example, you want to return user's full name, your User model will look something like this



                const User = db.Model.extend({
                tableName: 'users',
                hasSecurePassword: true,

                //be careful here, if you use arrow function `this` context will change
                //and your function won't work as expected

                returnFullName: function() {
                return this.get('firstname') + this.get('lastname');
                }
                });

                module.exports = User;


                then you will call this function like this



                User.forge().where({id: SOME_ID}).fetch()
                .then(function(user) {
                var fullName = user.returnFullName();
                });



                1. Class methods


                For example, you want to return user's email based on username, your User model will look something like this



                const User = db.Model.extend({
                tableName: 'users',
                hasSecurePassword: true
                }, {

                getUserEmail: function(SOME_USERNAME) {
                return User.forge().where({username: SOME_USERNAME}).fetch()
                .then(function (user) {
                if(user) {
                return Promise.resolve(user.get('email'));
                } else {
                return Promise.resolve(null);
                }
                });
                }
                });

                module.exports = User;


                then you can call this function like



                User.getUserEmail(SOME_USERNAME)
                .then(function(email) {
                console.log(email);
                });






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 7 at 0:09









                zerosand1s

                455313




                455313






















                    daniel gon is a new contributor. Be nice, and check out our Code of Conduct.










                     

                    draft saved


                    draft discarded


















                    daniel gon is a new contributor. Be nice, and check out our Code of Conduct.













                    daniel gon is a new contributor. Be nice, and check out our Code of Conduct.












                    daniel gon is a new contributor. Be nice, and check out our Code of Conduct.















                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53159554%2fadding-functions-to-a-knex-bookshelf-model-in-node-express%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest




















































































                    這個網誌中的熱門文章

                    Xamarin.form Move up view when keyboard appear

                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                    Anylogic : not able to use stopDelay()