javascript - 从 Rest API 中的 Sequelize 获取用户信息

标签 javascript node.js rest

我正在使用 nodejssequelize 创建 REST API,并且我有 2 个表:

  1. 用户表
  2. 好友表

/api/friends 

我获取了我所有的 friend 列表(存储在我的 friend 表中),但我不知道如何获取他们的名字(从用户表中)。

这是我获取好友列表的请求:

models.Friend.findAll({
  where: {
    $or: [{
      UserID: userFound.id
    },
    {
      idFriend: userFound.id
    }],
    status : "active"
  }
})

在图中,我向您展示了用户表和 friend 表 in the picture i show you the table user and friends

如何在我的请求中获取 friend 的姓名?

更新 这是我的用户模型

'use strict';
module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {
    email: DataTypes.STRING,
    username: DataTypes.STRING,
    password: DataTypes.STRING,
    isAdmin: DataTypes.BOOLEAN,
    isOut: DataTypes.BOOLEAN,
    bio: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here
    models.User.hasMany(models.Message)
    models.User.hasMany(models.Friend)
  };
  return User;
};

这是我 friend 的模型

    'use strict';
    module.exports = (sequelize, DataTypes) => {
      var Friend = sequelize.define('Friend', {
        UserID: DataTypes.INTEGER,
        idFriend: DataTypes.INTEGER,
        status: DataTypes.STRING
      }, {});
      Friend.associate = function(models) {
        // associations can be defined here
        models.Message.belongsTo(models.User, {
          foreignKey:{
            allowNull: false
          }
        })
      };
      return Friend;
    };


and my get friends function

 showFriend: function (req, res) {
        var headerAuth = req.headers['authorization'];
        var UserId = jwtUtils.getUserId(headerAuth);

        // Params
        asyncLib.waterfall([
            function (done) {
                models.User.findOne({
                    where: { id: UserId }
                })
                    .then(function (userFound) {
                        done(null, userFound);
                    })
                    .catch(function (err) {
                        return res.status(500).json({ 'error': 'unable to verify user' });
                    });
            },
            function (userFound, TargetFound, done) {
                models.Friend.findAll({
                    where: {
                        $or: [{
                            UserID: userFound.id
                        },
                        {
                            idFriend: userFound.id
                        }],
                    status : "active"
                    }
                })
                    .then(function (friends) {
                        if (friends) {
                            res.status(200).json(friends);
                        } else {
                            res.status(404).json({ "error": "no friends found" });
                        }
                    })
                    .catch(function (err) {
                        return res.status(500).json({ 'error': 'cannot find Friend' })
                    })
            }
        ], function (newFriend) {
            if (newFriend) {
                return res.status(201).json({
                    'newFriend': newFriend.id
                })
            } else {
                return res.status(500).json({ 'error': 'cannot add Friendss' })
            }
        });
    },

谢谢

最佳答案

如果 FriendUsers 关联,那么您必须在查询中包含它们:

models.Friend.findAll({
  where: {
    $or: [
      { UserID: userFound.id },
      { idFriend: userFound.id }
    ],
    status : "active"
  },
  include: [{
    model: models.User 
  }]
})

那么你应该能够执行以下操作:

const friends = models.Friend.findAll({ ... })
friends.forEach((friend) => {
  /* depends on your Naming Strategy, I'm assuming 
   `Users` will load as property 'User' on `Friends`,
    it depends on how your models and associations are defined
  */
  console.log(friend.User.username)
})

关于javascript - 从 Rest API 中的 Sequelize 获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49846636/

相关文章:

javascript - url参数及具体条件

javascript - 如何发送express文件夹中的一些特定的js、css?

node.js - Mongoose 将架构属性更改应用于文档

c# - Windows 服务每 6 小时做一次工作

java - 使用 Camel 进行 REST 服务调用,需要先调用身份验证 api

javascript - javascript 中的 IIFE 和全局作用域

javascript - 将成分 1 更改为 "Ingredient"+ 计数器的正则表达式

javascript - 这是在 Node 中进行依赖注入(inject)的正确方法吗?

api - 是否有任何 REST API 查询标准/DSL 来表达 GET URL 中的复杂过滤器?

javascript - onstart 和 oncomplete 在 p :commandLink 的数据表中不起作用