【问题标题】:Sequelize call structure续集调用结构
【发布时间】:2018-06-27 07:11:24
【问题描述】:

我正在使用 sequelize 并希望使用以下代码查询我的数据库:

models.user.findOne({ where: {email: req.body.email} }, (err, existingUser) => {
.... More code
}

但是代码块不会运行,所以我阅读了文档,他们给出的唯一示例使用以下结构:

models.user.findOne({ where: {title: 'aProject'} }).then(project => {
.... Code
})

我在第一个示例中做错了什么还是我无法使用该结构?

【问题讨论】:

    标签: javascript node.js express callback sequelize.js


    【解决方案1】:

    Sequelize.js 使用承诺。例如,当您使用findOne 时,将返回promise。所以尝试以下方法:

    models.user.findOne({ 
        where: {
            email: req.body.email
        }).then(existingUser => {
           //Do something
        }).catch(err => {
           //Do something with error
        });
    

    【讨论】:

      【解决方案2】:

      Sequelize>=1.7 查询返回一个 promise ,要解决它你需要使用 "then"

      nb:您可以直接从声明中使用模型,而不是像这样使用“models.user”:

      const Userdb = sequelize.define('userdb', {
       id : {
        primaryKey: true,
        autoIncrement:true,
        allowNull:false,
        type: Sequelize.INTEGER
      },
        email: {
        type: Sequelize.STRING,
        allowNull:false,
        validation:{
         isEmail:true
        },
      
      username: {
        type:  Sequelize.STRING,
        allowNull:false,
        min:6,
        max:25,
        notEmpty:true,
      }
      }
      

      要通过电子邮件获取用户,您可以这样做:

      Userdb.findOne({
                  where: { 
                          email: req.body.email
                         }
                     }).then((result)=>{
                         if(results) // there is one user 
                            {
                          // do something with resutls 
                            }else{
                              // no user with that mail 
                              }
                            })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-10
        • 2013-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多