node.js - Sequelize.js:findById() 未找到数据

标签 node.js sequelize.js

我想验证传入的 token ,并尝试通过 ID 查找用户:

module.exports = function (req) {
    var decodeToken = jwt.decode(req.cookies.token, JwtOptions.secretOrKey);
    db.users.findById(decodeToken.id).then(function (foundUser) {
        //It's example checking for self-learning
        if (foundUser.username == req.cookies.username) {
            return foundUser;
        }
        //Or more logic for token authentication
    }), function (error) {
        return error;
    }

但我得到“返回 false”。我查看 debuggindg 的foundUser 变量,它有消息

'Reference Error: foundUser is nor defined'

在控制台中我可以看到查询:

Executing (default): SELECT "id", "username", "email", "password", "createdAt", "updatedAt" FROM "users" AS "users" WHERE "users"."id" = 2;

我在数据库中有 id=2 的用户。 为什么不起作用?

<小时/>

添加:

我尝试了MWY的修改示例:

module.exports = function (req) {
    var decodeToken = jwt.decode(req.cookies.token, JwtOptions.secretOrKey);
    findUserById().then(function(foundUser) {
        //It's example checking for self-learning
        if (foundUser.username == req.cookies.username) {
            return foundUser;
        }
        //Or more logic for token authentication
    }), function (error) {
        return error;
    }

    function findUserById() {
        return db.users.findById(decodeToken.id).then(function (foundUser) {
            return foundUser;
        }), function (error) {
            return error;
        }
    }
}

并得到错误:

TypeError: findUserById(...).then is not a function

最佳答案

一定要记住异步

因为异步!你会先得到false,然后得到结果!

所以你可以这样写,在 ty.js 文件中

      module.exports = function (req) {
      var decodeToken = jwt.decode(req.cookies.token,   JwtOptions.secretOrKey);
      return db.users.findById(decodeToken.id).then(function (foundUser) {
    //It's example checking for self-learning
    if (foundUser.username == req.cookies.username) {
        return foundUser;
    }
    //Or more logic for token authentication
    }).catch(function (err) {
    return err;
     })
   };

tu.js文件中:

   var user = require('./ty');

   user().then(function (result) {
   //search findById result
   console.log(result)

   });

关于node.js - Sequelize.js:findById() 未找到数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43173383/

相关文章:

node.js - 如何将对象写入流?

mysql - 从 Sequelize 中的其他表查找计数

mysql - 有没有办法在 Sequelize 4 中进行 MySQL 全文搜索?

node.js - 无法解析 Node js 中的 sequelize 对象

node.js - 在 Sequelize 中创建具有关联的实例

node.js - Socket.io 使用默认命名空间和一些自定义命名空间,不起作用

JavaScript promise 不返回对象

sequelize.js - 将外键目标与源序列化

node.js - 我无法在 Node 中发出 Web 请求

node.js - 包含使用 Mongoose 查询 MongoDB 数组