Sequelize检查行存在,并返回布尔值

时间:2019-05-15 23:02:22

标签: promise sequelize.js

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

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

这是我当前收到的结果:


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

我知道这是诺言的问题,但我无法解决。


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 
    }
}

1 个答案:

答案 0 :(得分:0)

尝试以下操作:

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