Error: Model attribute missing in Adonis JS v5 relationship

Recently, I started diving into the Adonis framework (v5) and decided to build a todo list api as part of my learning process.

However, I'm facing an issue concerning the relationship between the User and Todo entities.

Let me show you the models for better understanding:

// file: app/Models/Todo.ts

export default class Todo extends BaseModel {
  @column({ isPrimary: true })
  public id: number

  @belongsTo(() => User, {
    foreignKey: 'id',
  })
  public author: BelongsTo<typeof User>

  @column()
  public completed: boolean

  @column()
  public title: string

  @column()
  public description: string | null

  @column.dateTime({ autoCreate: true })
  public createdAt: DateTime

  @column.dateTime({ autoCreate: true, autoUpdate: true })
  public updatedAt: DateTime
}
// file: app/Models/User.ts

export default class User extends BaseModel {
  @column({ isPrimary: true })
  public id: number

  @column()
  public username: string

  @column({ serializeAs: null })
  public password: string

  @hasMany(() => Todo, {
    foreignKey: 'author',
  })
  public todos: HasMany<typeof Todo>

  @column.dateTime({ autoCreate: true })
  public createdAt: DateTime

  @column.dateTime({ autoCreate: true, autoUpdate: true })
  public updatedAt: DateTime

  @beforeSave()
  public static async hashPassword(user: User) {
    if (user.$dirty.password) {
      user.password = await Hash.make(user.password)
    }
  }
}

I omitted the migration files, but can provide them if necessary. The challenge here is that I expect to be able to save Users and Todo entries in the database while linking each todo entry to its respective author, following the documentation provided here.

To troubleshoot, I used the node ace repl command like this:

// log of running the commands in the AdonisJS v5 REPL
> loadModels()
recursively reading models from "app/Models"
Loaded models module. You can access it using the "models" variable
> undefined
> const testUser = await models.User.create({ username: 'testUser', password: 'password' })
undefined
> await testUser.related('todos').create({ title: 'Example todo entry' })
Uncaught:
Exception: E_MISSING_MODEL_ATTRIBUTE: "User.todos" expects "author" to exist on "Todo" model, but is missing
    at <my-app-directory>\REPL23:1:39
    at Proxy.related (<my-app-directory>\node_modules\@adonisjs\lucid\build\src\Orm\BaseModel\index.js:1436:18)
    at HasMany.boot (<my-app-directory>\node_modules\@adonisjs\lucid\build\src\Orm\Relations\HasMany\index.js:74:12)
    at KeysExtractor.extract (<my-app-directory>\node_modules\@adonisjs\lucid\build\src\Orm\Relations\KeysExtractor.js:28:39)
    at Array.reduce (<anonymous>)
    at <my-app-directory>\node_modules\@adonisjs\lucid\build\src\Orm\Relations\KeysExtractor.js:32:23
>

The error message seems confusing because the author attribute does exist in the Todo model. Any ideas on how to resolve this issue and successfully run my todo app? Your help is greatly appreciated!

Thank you in advance!

Answer №1

You're making an error by forgetting to include a field in your model.

To ensure all fields are properly defined, use the @column() decorator for each one. In this case, it appears you have omitted the column author.

When setting up a relationship, make sure there is one column serving as the foreign key and one defining the relationship itself.

If we take, for example, that you have a column user_id within your todos table, then be sure to add the user_id column to your Todo model as well.

Here's a corrected version:

class User extends BaseModel {
  // ...
  @hasMany(() => Todo)
  todos: HasMany<typeof Todo>
}

class Todo extends BaseModel {
  @column()
  user_id: number

  @belongsTo(() => User)
  author: BelongsTo<typeof User>
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimize the performance of filtering large GeoJSON files using Ajax in leaflet for the

I am managing four 2MB geoJson files with four different Layers that need to be loaded. Each layer is loaded using the following code: LayerBoon = L.geoJSON.ajax(URL, {pointToLayer:returnBoonMarker, filter:filtertext}); There is also a button click functi ...

Combining CSS and JS files for accordion list - experiencing issues when used separately

Recently, I've been trying to create an accordion list and stumbled upon some code (HTML, CSS, and JS) on www.w3schools.com. When I have the code all in one document and run it as a single .html file, everything works perfectly. However, when I split ...

Jquery click event functioning on one page but malfunctioning on another

On one page, the dropdown click function is working, but on another page, even though it's the same component and JavaScript file, it's not working. Here's the component: <li class="nav-item dropdown"> <a clas ...

Exploring Object Elements using For Loop

After trying numerous methods, I am still puzzled by this issue. I have a feeling that the solution is going to be something very simple, but nevertheless, I need to ask for help. This is the function I'm dealing with: Module.load = function(a) { ...

The amazingly efficient Chrome quick find feature, accessible by pressing the powerful combination of Ctrl + F, ingeniously

Currently using Google Chrome version 29.0.1547.62 m. I've employed the CSS attribute overflow set to hidden on the parent element, which renders some of my DIV elements hidden from view. Additionally, these concealed DIV elements are adjusted in pos ...

Encountering Build Issue: "NgSemanticModule is not recognized as an NgModule" persists despite inclusion of dependencies and importing into primary module

I have posted my module, component, and package file here. I am attempting to implement a click event with ngif, but I keep encountering an error. The specific error message is "ERROR in NgSemanticModule is not an NgModule". I'm unsure if this error ...

How to retrieve URL parameters from within the when() function in AngularJS

Consider the code snippet below: $routeProvider.when('/movies/:type', { title: 'Movies', templateUrl: 'pages/movies/movies.html', controller: 'MoviesCtrl' }); Is there a way to retriev ...

Align the camera to be perpendicular with the ground

Ensuring that my fly camera always remains parallel to the ground is crucial to me. Specifically, I need my camera's right vector to always be (1,0,0). To achieve this, I have developed a customized Camera Controller in three.js that simulates unique ...

Processing Data with JavaScript

I am new to working with JavaScript, coming from the Python world. I need some assistance. Currently, I am retrieving data from the back end that has the following structure: { "Airports": { "BCN": { "Arrivals": [ ...

Updating the authentication code in passport.js

In the project, there is a passport.js file that contains authentication related code: const axios = require('axios') const uuid = require('uuid/v4') const passport = require('passport') const LocalStrategy = require('pa ...

Performing Jasmine unit testing on a component that relies on data from a service, which itself retrieves data from another service within an Angular 2+ application

Attempting to implement unit testing for a service using httpmock has been challenging. The service in question utilizes a method to make http get calls, but I have encountered difficulties in writing the test cases. saveservice.service.ts -- file const ...

The elusive three.module.js file has gone missing, leaving behind a trail of 404 errors

It seems like a simple mistake, but I'm encountering a 404 error for a file that actually exists: http://localhost:8000/Desktop/Skeletor/js/build/three.module.js net::ERR_ABORTED 404 (File not found) The correct path should be http://localhost: ...

What causes an error when trying to access with the member access operator?

When dealing with object properties in the code snippet below, an error is thrown when trying to access the object using the Member Access. Why does this happen? var d = {a: 10, b: 20, c:30}; var keys = Object.getOwnPropertyNames(d); ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

Experiencing browser crashes following the incorporation of asynchronous functions into a JavaScript file. Seeking solutions to resolve this

In my recent project, I developed a basic online store application using vanilla javascript and ES6 classes. The shop items are stored in a JSON file which I used to populate the user interface. To implement functions like "addToCart", "quantityChange", a ...

What are the reasons behind the significant difference in speed between using Node's Object.create(foo) and new Foo()?

For my Sudoku solver in JavaScript, I decided to take a purely functional approach by using immutable 9x9 puzzle arrays. Every time a new number is inserted, a new array is created. Implementation 1: New SudokuPuzzle In the initial version, I utilized th ...

Trigger Angular Animation when there is a modification in the DOM element's appearance or styling

I've been working on implementing a fade-in animation in my Angular App that triggers every time the background changes, but I'm facing some challenges with it. Here's the relevant code snippet: HTML: <div @fadeIn [style.backgroundImag ...

What is the best way to name a force-directed Graph using d3?

I'm struggling to label the nodes in my force-directed graph created with d3.js. Despite trying various solutions from StackOverflow and online tutorials, I believe my issues stem from a lack of fundamental understanding of JavaScript. I've expe ...

Trigger a random tune when hovering the mouse

I need help figuring out how to make a fixed image on my page trigger a random sound track when hovered over. The sound could be one of five different tracks. Here is the HTML for my image: <img src="images/Airplane.png" class="Airplane-photo"> Bel ...

The success function in Ajax is constantly elusive, while the error function prevails. The data just can't seem to make it to the destination file

Thank you for your patience. This marks my initial post to the best of my recollection. The section below showcases a snippet from my calendar.js script. My current objective involves sending data obtained from a modal window in index.php over to sql.php. ...