【问题标题】:Sequelize check row exists, and return booleanSequelize 检查行是否存在,并返回布尔值
【发布时间】:2019-05-16 10:06:54
【问题描述】:

我正在尝试使用 Sequelize 查询关联表以查看是否有一个用户正在关注另一个用户。如果关系存在,我想返回 true。如果不是,则返回 false。我想将此响应返回到 toProfileJSONFor 的“以下”部分(见下文)。

根据日志记录,一切似乎都按预期工作,除了我收到的是一个承诺,而不是我的布尔值。我已经阅读了尽可能多的关于承诺的内容,但似乎仍然无法弄清楚我的问题。

这是我目前收到的结果:


{
    "profile": {
        "username": "superman1",
        "bio": null,
        "image": "",
        "following": {
            "isFulfilled": false,
            "isRejected": false
        }
    }
}

我知道这是 Promise 的问题,但我无法找到解决方案。


User.prototype.toProfileJSONFor = function(user){
  return {
    username: this.username,
    bio: this.bio,
    image: this.image || 'genericImage.jpg',
    following: user.isFollowing(this.id) //this is where I am having issues
  };

User.prototype.isFollowing = function(id){
  let userId = this.id; // current userId
  let followId = id; //profile Id


  return FollowerFolloweds.findAll({
    where: { followedId: followId, followerId: userId},raw : true })
    .then(function(result) {
      if(result.length !=0){
        return true;
      }  {
        return false;
      }

    })
}

预期的结果是:

{
    "profile": {
        "username": "superman1",
        "bio": null,
        "image": "",
        "following": true 
    }
}

【问题讨论】:

    标签: promise sequelize.js


    【解决方案1】:

    尝试以下方法:

    User.prototype.toProfileJSONFor = function(user){
      return user.isFollowing(this.id)
        .then((following) => {
            username: this.username,
            bio: this.bio,
            image: this.image || 'genericImage.jpg',
            following
        });
    }
    

    【讨论】:

    • 嗨 - 非常感谢您的评论。不幸的是,这返回了以下 { "profile": { "isFulfilled": false, "isRejected": false } }
    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 2023-03-28
    • 1970-01-01
    • 2023-01-13
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多