简体   繁体   中英

Nodejs Sequelize Many to many relationship

I am trying to fetch data from DB with sequelize. The many to many relationships between users and roles. When i fetch the users does not include the roles.

The code look like:

user model

 // model defines the user objects const userModel = (sequelize, Sequelize) => { const users = sequelize.define("user", { id: { type: Sequelize.STRING, allowNull: false, primaryKey: true, }, firstname: { allowNull: false, type: Sequelize.STRING, }, lastname: { allowNull: false, type: Sequelize.STRING, }, password: { allowNull: false, type: Sequelize.STRING, }, email: { allowNull: false, type: Sequelize.STRING, }, image: { allowNull: true, type: Sequelize.STRING, }, }); //don not show password and id users.prototype.toJSON = function () { let values = Object.assign({}, this.get()); delete values.password; delete values.id; return values; }; return users; }; export default userModel;

Roles model

 // model defines the events objects const rolesModel = (sequelize, Sequelize) => { const roles = sequelize.define("roles", { id: { type: Sequelize.STRING, allowNull: false, primaryKey: true, }, name: { allowNull: false, type: Sequelize.STRING, }, description: { allowNull: true, type: Sequelize.STRING, }, }); return roles; }; export default rolesModel;

The associations:

 db.users.associate = (db) => { db.users.belongsToMany(db.roles, { through: "userroles", constraints: false, foreignKey: "rolesId", }); }; db.roles.associate = (db) => { db.roles.belongsToMany(db.users, { through: "userroles", constraints: false, foreignKey: "userId", }); };

There are two controller functions that are adding and fetching the user data

Controller

 User.create(userDetails).then(() => { let roles = req.body.roles; roles.forEach(async (element) => { let role = await Roles.findByPk(element); if (role) { await Userroles.create({ id: uniqid(), rolesId: element, userId: userId, }); } else { logger.warn(`tried adding to ${userId} a none existent role`); } }); }) // get user let user = await User.findOne({ where: { email: username }, include: { model: db.roles }, });

So the roles are only a empty array when I try getting user details: "firstname": "Mathew", "lastname": "Murimi", "email": "******@gmail.com", "image": null, "createdAt": "2022-02-12T22:56:40.000Z", "updatedAt": "2022-02-12T22:56:40.000Z", "roles": []

// Receive the user created in the then, add the id of "newUser" in "userId"

User.create(userDetails)
      .then((**newUser**) => {
        let roles = req.body.roles;
        roles.forEach(async (element) => {
          let role = await Roles.findByPk(element);
          if (role) {
            await Userroles.create({
              id: uniqid(),
              rolesId: element,
              userId: **newUser.id**,
            });
          } else {
            logger.warn(`tried adding to ${**newUser.id**} a none existent role`);
          }
        });
      })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM