javascriptnode.jsadonis.jsadonisjs-acelucid

Adonis custom command fail to update database


I created a custom command in my AdonisJs project (I use v6).

I import a model and try to insert objects into it:

import Country from '../app/models/country.js'
import Region from '../app/models/region.js'
import City from '../app/models/city.js'

async run() {
  await Country.create({
    name: 'Andorra',
    isoCode: 'AD',
    numLevels: 2,
    levelNames: "['state','city']",
  })

I get this error:

[ error ] Cannot read properties of undefined (reading 'insert')

I will be grateful for any hint or idea how to either solve or debug this error.


Solution

  • It took me time to solve it, in case it will help someone I will leave here the solution.

    In order to be able to use services, models, etc. in Adonis script, you need to launch app.
    The way to do it:

    export default class MyScript extends BaseCommand {
      static options: CommandOptions = {
        startApp: true, // <- this options indicates to start the app
        allowUnknownFlags: false,
        staysAlive: false,
      }