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

Using websockets in a React client application

Attempting to establish a connection with a backend layer running on localhost, here is the provided source code: const { createServer } = require("http"); const cors = require("cors"); const photos = require("./photos"); const app = require("express")( ...

What is the best way to redirect before displaying a page in Next.js?

Is it possible to redirect a user before rendering a page in Next.js? Currently, my code looks like this: import { useRouter } from 'next/router'; export default function RedirectPage() { const router = useRouter(); router.push('/p ...

What is the best way to access the element menu with element-ui?

I am looking for a way to programmatically open an element in my menu, but I haven't been able to find any information on how to do it. HTML <script src="//unpkg.com/vue/dist/vue.js"></script> <script src="//unpkg.com/<a hr ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

Identifying Master Page Controls Post-Rendering

Within my asp.net projects, I have noticed a discrepancy in the control id on the master page's Contentplaceholder1. On my local server, the id appears as "ctl00_Contentplaceholder1_control" after rendering. However, when the application is deployed t ...

How can I confirm if a class is an instance of a function-defined class?

I have been attempting to export a class that is defined within a function. In my attempts, I decided to declare the class export in the following way: export declare class GameCameraComponent extends GameObject { isMainCamera: boolean; } export abstra ...

In Javascript, an error occurs when something is undefined

I've been grappling with a Javascript issue and seem to have hit a roadblock. In Firefox's console, I keep encountering an error message that says "info[last] is undefined," and it's leaving me puzzled. The problematic line appears to be nu ...

A guide on setting up fixed row numbers in MUI-X DataGrid

One challenge I am facing is rendering the row numbers in a table so that they remain static even when columns are sorted or filtered. I attempted to use the getRowIndexRelativeToVisibleRows method of the grid API, but unfortunately, it does not work as ex ...

Changing the InnerHTML of a tag in JavaScript using class and id attributes

When it comes to handling these links <div class="post_actions"> <a class="color-transition article_delete" href=""><i class="fa fa-pencil"></i></a> <a class="color-transition article_edit" href="#" id="1">< ...

Using JavaScript to toggle the display of a label element

Greetings everyone! I recently posted a question on this thread about replacing input with javascript, but ended up abandoning that idea. Instead, I decided to explore a different approach... I made the background of my password field transparent and posi ...

What is the method for assigning a value to a JSON object using data from another JSON object?

I am faced with the task of setting the seqNo property in one JSON object, b, based on the id from another JSON object, a. How can I achieve this? var a = [{id: "Make", seqNo: 4}, {id: "Model", seqNo: 1}, {id: "XModel", seqNo: 2 ...

Comparison of element state prior to and post editing (with contentEditable)

Exploring how elements within a div can be monitored for changes made by the user (thanks to contentEditable), I created a sample page with the following setup: before_html = $("#example_div").children(); $("#differences_button").on("click", ...

Using $anchorScroll in Angular to create an anchor link that links to the same page but with a style change seems to be ineffective

I have a simple Angular view that includes a menu. Each item in the menu serves as a link to a specific section of the same page. I am utilizing $anchorScroll to achieve this functionality and it is functioning correctly. However, I am encountering an issu ...

IE9 causing issues with Angularjs ng-route - views fail to display

I am new to AngularJS and currently working on developing an application using AngularJS along with Coldfusion for database data retrieval. However, I am facing compatibility issues specifically with IE9 (which is the default browser in my office). The ap ...

Dynamically transferring data from PHP to JavaScript in dynamically generated HTML elements

I have a collection of entities retrieved from a database, each entity containing its own unique GUID. I am showcasing them on a webpage (HTML) by cycling through the entities array and placing each one within a new dynamically generated div element. < ...

Discovering the clicked element within a QueryList<ElementRef> in Angular

Having a ElementRef(QueryList) of a group of dynamically created Table cells (td html elements) using ViewChildren, I have successfully debugged and verified the availability of the element set. When clicking on a specific td html element, a function is c ...

When attempting to swap out ":customimage:" with an image in a React.js HTML view, the result displayed is [object Object]

I have created a function below: WordColonsToImage(comment) { var newcomment = comment.replace(/:wave:\s*/g, <img src={wavinghand} />) return newcomment } Here is an example: WordColonsToImage("Hi! :wave:") whi ...

Using jQuery to toggle visibility based on scroll position

Recently, I received a web template equipped with a jQuery library called sticky, which essentially makes the navigation "stick" to the top of the page as you scroll. Now, my goal is to integrate a logo into the navigation once it reaches its final positio ...

Challenges with implementing singleSelect feature in MUI-X DataGrid

Encountering an issue with the singleSelect type on the community version of x-data-grid. The problem arises when attempting to edit a row, where my singleSelect consists of the following data set. Here is how I have configured my DataGrid setup. Although ...

activated by selecting a radio button, with a bootstrap dropdown menu

I'm having trouble triggering the dropdown in Bootstrap by clicking on a radio button. It seems like a simple task, but I've been struggling with it all day. According to Bootstrap documentation, you can activate the dropdown using a hyperlink o ...