I have two tables, 'users' and 'clubs,' that are related with a one-to-many relation. This means each user can be associated with many clubs, and each club is owned by one user. However, when attempting to create a new club and set its user to the current user record, an error is encountered: 'Cannot read property 'set' of undefined.'.
The piece of code that throws the error:
@writer async addClub(name, location) {
const newClub = await this.collections.get('clubs').create( club => {
club.user.set(this) // <= this throws "Cannot read property 'set' of undefined"
club.name = name
club.location =location
})
return newClub
}
Models :
class User extends Model {
static table = 'users';
static associations = {
clubs: { type: 'has_many', foreignKey: 'user_id' },
}
@text('email') email;
@field('password') password;
@text('first_name') firstName;
@text('last_name') lastName;a
@text('username') username;
@readonly @date('created_at') createdAt;
@field('is_active') isActive;
@field('is_deleted') isDeleted;
@field('is_admin') isAdmin;
@field('is_onboarded') isOnboarded;
@children('clubs') clubs;
@writer async addClub(name, location) {
const newClub = await this.collections.get('clubs').create( club => {
club.user.set(this)
club.name = name
club.location =location
})
return newClub
}
}
class Club extends Model {
static table = 'clubs';
static associations = {
users: { type: 'belongs_to', key: 'user_id' },
groups: { type: 'has_many', foreignKey: 'club_id' },
}
@text('name') name;
@text('location') location;
@text('logo') logo;
@readonly @date('created_at') createdAt;
@readonly @date('updated_at') updatedAt;
@field('is_active') isActive;
@field('is_deleted') isDeleted;
@relation('users', 'user_id') user;
@children('groups') groups;
}
List of dependencies for this project:
"react-native": "0.72.7",
"@nozbe/watermelondb": "^0.27.1",
"@babel/plugin-proposal-decorators": "^7.23.3",
"@babel/preset-env": "^7.20.0",
Babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
["module:react-native-dotenv",
{
"moduleName": "@env",
"path": ".env",
"blacklist": null,
"whitelist": null,
"safe": false,
"allowUndefined": true
}
],
["@babel/plugin-proposal-decorators", { "version": "legacy" }],
'react-native-reanimated/plugin'
],
};