What's Wrong With My Sequelize belongsToMany Search?

252 Views Asked by At

I'm trying to use Sequelize joins for the first time. I seem to have done everything exactly as per the docs, but for some reason my related records aren't being returned by the search.

SEQUELIZE MODELS

const apptsModel = db.define('Appts', {
    id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
    [.....]});


const UserDataModel = db.define('UserData', {
    [.....]
    userID: {type: Sequelize.STRING},
});

apptsModel.belongsToMany(UserDataModel, {through: 'ApptsToUsers', foreignKey: 'ApptID'});
UserDataModel.belongsToMany(apptsModel, {through: 'ApptsToUsers', foreignKey: 'UserDatumUserID'});

const UserData = db.models.UserData;
const Appts = db.models.Appts;

export {UserData, Appts };

My belongsToMany table records are being successfully created, including the correct entries in the ApptsToUsers table. But when I try to do a find on a given Appt to return the related records from the UserData, no related data comes back.

SEARCH CODE

return Promise.resolve()
     .then(() => {
        var participants = connectors.Appts.findAll({ where: {id: 10}, include: [ connectors.UserData ] });
        return participants;
    })
    .then(participants => {
     //RELATED DATA NOT FOUND
    })
    .catch((err)=>{
        console.log(err);
    });

What am I missing?

Thanks in advance to all for any info.

1

There are 1 best solutions below

0
On BEST ANSWER

I solved this by renaming UserDataModel.userID field to UserDataModel.id (deleting the previous UserDataModel.id field), and changing the following code to omit the foreignKey option:

apptsModel.belongsToMany(UserDataModel, {through: 'ApptsToUsers'});
UserDataModel.belongsToMany(apptsModel, {through: 'ApptsToUsers'});

Sequelize defaults to expecting the fields it's looking for in this case to be named 'id'.