Sequelize Model Duplicate value check












0















i am new in sequelize and ORMs and i am trying to create a model. This is what i have:



/* Carrier model definition */
const carrier = sequelize.define('carrier', {
/* The unique carrier id */
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
/* The iata code of the carrier */
iata: {
type: Sequelize.STRING,
validate: {
is: {
args: ["^[A-Z]{1}[0-9]{1}$|^[A-Z]{1}[A-Z]{1}$|^[0-9]{1}[A-Z]{1}$|^s*$"],
msg: "Carrier iata code is invalid."
}
}
},
/* The icao code of the carrier */
icao: {
type: Sequelize.STRING,
validate: {
is: {
args: ["^[A-Z]{3}$|^s*$"],
msg: "Carrier icao code is invalid."
}
}
},
/* The deleted flag of the carrier */
isdeleted: {
type: Sequelize.INTEGER,
validate: {
isIn: {
args: [
[0, 1]
],
msg: "Carrier "is deleted value" can be 0 or 1."
}
}
}
}, {
/* Perform model validations */
validate: {
carrierValidator() {

/* Ensure that at least an iata or an icao code exists */
if ((this.iata == "") && (this.icao == "")) {

throw new Error('Carrier must have at least an iata code or an icao code or both.');

}

}
},
/* Apply hooks */
hooks: {
beforeValidate: (carrier, options) => {

/* Capitalize carrier iata code */
carrier.iata = (typeof carrier.iata === 'undefined') ? "" : carrier.iata.toUpperCase();

/* Capitalize carrier icao code */
carrier.icao = (typeof carrier.icao === 'undefined') ? "" : carrier.icao.toUpperCase();

/* Set default isdeleted value to 0 */
carrier.isdeleted = (typeof carrier.isdeleted === 'undefined') ? 0 : parseInt(carrier.isdeleted);

}
}

})


The isdeleted property is a column which defines if an entry is deleted or not. If it is deleted it's value is 1 and if not 0.



Now, i want to prevent the insert of a new carrier, if one of the following is true:




  1. If a carrier with the same iata code, and isdeleted = 0 exists

  2. If a carrier with the same icao code, and isdeleted = 0 exists


I managed to achieve it, by adding the following block inside validate (for iata case):



if (this.iata != ""){

sequelize.models.carrier.findAndCountAll({
where: {
iata: this.iata,
isdeleted:0
}
}).then((result) => {

if (result.rows != 0){

throw new Error("Carrier iata code already exists.");

}

})

}


and when i attempt to insert a duplicate i get a very ugly response:



enter image description here



Is there a way to get an instance of ValidationError in order to handle it and display iteasier?










share|improve this question





























    0















    i am new in sequelize and ORMs and i am trying to create a model. This is what i have:



    /* Carrier model definition */
    const carrier = sequelize.define('carrier', {
    /* The unique carrier id */
    id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
    },
    /* The iata code of the carrier */
    iata: {
    type: Sequelize.STRING,
    validate: {
    is: {
    args: ["^[A-Z]{1}[0-9]{1}$|^[A-Z]{1}[A-Z]{1}$|^[0-9]{1}[A-Z]{1}$|^s*$"],
    msg: "Carrier iata code is invalid."
    }
    }
    },
    /* The icao code of the carrier */
    icao: {
    type: Sequelize.STRING,
    validate: {
    is: {
    args: ["^[A-Z]{3}$|^s*$"],
    msg: "Carrier icao code is invalid."
    }
    }
    },
    /* The deleted flag of the carrier */
    isdeleted: {
    type: Sequelize.INTEGER,
    validate: {
    isIn: {
    args: [
    [0, 1]
    ],
    msg: "Carrier "is deleted value" can be 0 or 1."
    }
    }
    }
    }, {
    /* Perform model validations */
    validate: {
    carrierValidator() {

    /* Ensure that at least an iata or an icao code exists */
    if ((this.iata == "") && (this.icao == "")) {

    throw new Error('Carrier must have at least an iata code or an icao code or both.');

    }

    }
    },
    /* Apply hooks */
    hooks: {
    beforeValidate: (carrier, options) => {

    /* Capitalize carrier iata code */
    carrier.iata = (typeof carrier.iata === 'undefined') ? "" : carrier.iata.toUpperCase();

    /* Capitalize carrier icao code */
    carrier.icao = (typeof carrier.icao === 'undefined') ? "" : carrier.icao.toUpperCase();

    /* Set default isdeleted value to 0 */
    carrier.isdeleted = (typeof carrier.isdeleted === 'undefined') ? 0 : parseInt(carrier.isdeleted);

    }
    }

    })


    The isdeleted property is a column which defines if an entry is deleted or not. If it is deleted it's value is 1 and if not 0.



    Now, i want to prevent the insert of a new carrier, if one of the following is true:




    1. If a carrier with the same iata code, and isdeleted = 0 exists

    2. If a carrier with the same icao code, and isdeleted = 0 exists


    I managed to achieve it, by adding the following block inside validate (for iata case):



    if (this.iata != ""){

    sequelize.models.carrier.findAndCountAll({
    where: {
    iata: this.iata,
    isdeleted:0
    }
    }).then((result) => {

    if (result.rows != 0){

    throw new Error("Carrier iata code already exists.");

    }

    })

    }


    and when i attempt to insert a duplicate i get a very ugly response:



    enter image description here



    Is there a way to get an instance of ValidationError in order to handle it and display iteasier?










    share|improve this question



























      0












      0








      0








      i am new in sequelize and ORMs and i am trying to create a model. This is what i have:



      /* Carrier model definition */
      const carrier = sequelize.define('carrier', {
      /* The unique carrier id */
      id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false
      },
      /* The iata code of the carrier */
      iata: {
      type: Sequelize.STRING,
      validate: {
      is: {
      args: ["^[A-Z]{1}[0-9]{1}$|^[A-Z]{1}[A-Z]{1}$|^[0-9]{1}[A-Z]{1}$|^s*$"],
      msg: "Carrier iata code is invalid."
      }
      }
      },
      /* The icao code of the carrier */
      icao: {
      type: Sequelize.STRING,
      validate: {
      is: {
      args: ["^[A-Z]{3}$|^s*$"],
      msg: "Carrier icao code is invalid."
      }
      }
      },
      /* The deleted flag of the carrier */
      isdeleted: {
      type: Sequelize.INTEGER,
      validate: {
      isIn: {
      args: [
      [0, 1]
      ],
      msg: "Carrier "is deleted value" can be 0 or 1."
      }
      }
      }
      }, {
      /* Perform model validations */
      validate: {
      carrierValidator() {

      /* Ensure that at least an iata or an icao code exists */
      if ((this.iata == "") && (this.icao == "")) {

      throw new Error('Carrier must have at least an iata code or an icao code or both.');

      }

      }
      },
      /* Apply hooks */
      hooks: {
      beforeValidate: (carrier, options) => {

      /* Capitalize carrier iata code */
      carrier.iata = (typeof carrier.iata === 'undefined') ? "" : carrier.iata.toUpperCase();

      /* Capitalize carrier icao code */
      carrier.icao = (typeof carrier.icao === 'undefined') ? "" : carrier.icao.toUpperCase();

      /* Set default isdeleted value to 0 */
      carrier.isdeleted = (typeof carrier.isdeleted === 'undefined') ? 0 : parseInt(carrier.isdeleted);

      }
      }

      })


      The isdeleted property is a column which defines if an entry is deleted or not. If it is deleted it's value is 1 and if not 0.



      Now, i want to prevent the insert of a new carrier, if one of the following is true:




      1. If a carrier with the same iata code, and isdeleted = 0 exists

      2. If a carrier with the same icao code, and isdeleted = 0 exists


      I managed to achieve it, by adding the following block inside validate (for iata case):



      if (this.iata != ""){

      sequelize.models.carrier.findAndCountAll({
      where: {
      iata: this.iata,
      isdeleted:0
      }
      }).then((result) => {

      if (result.rows != 0){

      throw new Error("Carrier iata code already exists.");

      }

      })

      }


      and when i attempt to insert a duplicate i get a very ugly response:



      enter image description here



      Is there a way to get an instance of ValidationError in order to handle it and display iteasier?










      share|improve this question
















      i am new in sequelize and ORMs and i am trying to create a model. This is what i have:



      /* Carrier model definition */
      const carrier = sequelize.define('carrier', {
      /* The unique carrier id */
      id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false
      },
      /* The iata code of the carrier */
      iata: {
      type: Sequelize.STRING,
      validate: {
      is: {
      args: ["^[A-Z]{1}[0-9]{1}$|^[A-Z]{1}[A-Z]{1}$|^[0-9]{1}[A-Z]{1}$|^s*$"],
      msg: "Carrier iata code is invalid."
      }
      }
      },
      /* The icao code of the carrier */
      icao: {
      type: Sequelize.STRING,
      validate: {
      is: {
      args: ["^[A-Z]{3}$|^s*$"],
      msg: "Carrier icao code is invalid."
      }
      }
      },
      /* The deleted flag of the carrier */
      isdeleted: {
      type: Sequelize.INTEGER,
      validate: {
      isIn: {
      args: [
      [0, 1]
      ],
      msg: "Carrier "is deleted value" can be 0 or 1."
      }
      }
      }
      }, {
      /* Perform model validations */
      validate: {
      carrierValidator() {

      /* Ensure that at least an iata or an icao code exists */
      if ((this.iata == "") && (this.icao == "")) {

      throw new Error('Carrier must have at least an iata code or an icao code or both.');

      }

      }
      },
      /* Apply hooks */
      hooks: {
      beforeValidate: (carrier, options) => {

      /* Capitalize carrier iata code */
      carrier.iata = (typeof carrier.iata === 'undefined') ? "" : carrier.iata.toUpperCase();

      /* Capitalize carrier icao code */
      carrier.icao = (typeof carrier.icao === 'undefined') ? "" : carrier.icao.toUpperCase();

      /* Set default isdeleted value to 0 */
      carrier.isdeleted = (typeof carrier.isdeleted === 'undefined') ? 0 : parseInt(carrier.isdeleted);

      }
      }

      })


      The isdeleted property is a column which defines if an entry is deleted or not. If it is deleted it's value is 1 and if not 0.



      Now, i want to prevent the insert of a new carrier, if one of the following is true:




      1. If a carrier with the same iata code, and isdeleted = 0 exists

      2. If a carrier with the same icao code, and isdeleted = 0 exists


      I managed to achieve it, by adding the following block inside validate (for iata case):



      if (this.iata != ""){

      sequelize.models.carrier.findAndCountAll({
      where: {
      iata: this.iata,
      isdeleted:0
      }
      }).then((result) => {

      if (result.rows != 0){

      throw new Error("Carrier iata code already exists.");

      }

      })

      }


      and when i attempt to insert a duplicate i get a very ugly response:



      enter image description here



      Is there a way to get an instance of ValidationError in order to handle it and display iteasier?







      error-handling orm sqlite3 sequelize.js






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 18:05







      George R.

















      asked Nov 21 '18 at 14:24









      George R.George R.

      156




      156
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Well it looks like i was a bit tired and i missed a return...



          if (this.iata != ""){

          return sequelize.models.carrier.findAndCountAll({
          where: {
          iata: this.iata,
          isdeleted:0
          }
          }).then((result) => {

          if (result.rows != 0){

          throw new Error("Carrier iata code already exists.");

          }

          })

          }


          Thanks to florin from sequelize slack!






          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',
            autoActivateHeartbeat: false,
            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
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53414213%2fsequelize-model-duplicate-value-check%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Well it looks like i was a bit tired and i missed a return...



            if (this.iata != ""){

            return sequelize.models.carrier.findAndCountAll({
            where: {
            iata: this.iata,
            isdeleted:0
            }
            }).then((result) => {

            if (result.rows != 0){

            throw new Error("Carrier iata code already exists.");

            }

            })

            }


            Thanks to florin from sequelize slack!






            share|improve this answer




























              0














              Well it looks like i was a bit tired and i missed a return...



              if (this.iata != ""){

              return sequelize.models.carrier.findAndCountAll({
              where: {
              iata: this.iata,
              isdeleted:0
              }
              }).then((result) => {

              if (result.rows != 0){

              throw new Error("Carrier iata code already exists.");

              }

              })

              }


              Thanks to florin from sequelize slack!






              share|improve this answer


























                0












                0








                0







                Well it looks like i was a bit tired and i missed a return...



                if (this.iata != ""){

                return sequelize.models.carrier.findAndCountAll({
                where: {
                iata: this.iata,
                isdeleted:0
                }
                }).then((result) => {

                if (result.rows != 0){

                throw new Error("Carrier iata code already exists.");

                }

                })

                }


                Thanks to florin from sequelize slack!






                share|improve this answer













                Well it looks like i was a bit tired and i missed a return...



                if (this.iata != ""){

                return sequelize.models.carrier.findAndCountAll({
                where: {
                iata: this.iata,
                isdeleted:0
                }
                }).then((result) => {

                if (result.rows != 0){

                throw new Error("Carrier iata code already exists.");

                }

                })

                }


                Thanks to florin from sequelize slack!







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 21 '18 at 20:48









                George R.George R.

                156




                156
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53414213%2fsequelize-model-duplicate-value-check%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    'app-layout' is not a known element: how to share Component with different Modules

                    android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                    WPF add header to Image with URL pettitions [duplicate]