"Converting circular structure to JSON" error when querying with User model


#1

I wanted to quickly test something so rather than making a controller and validator file, I decided to write everything in the routes.js.

My welcome.edge (relevant portion)

<form method="POST" action="/users">
        {{ csrfField() }}
        <input type="text" name="username" />
        <button type="submit"> Submit </button>
      </form>
      @if(hasErrorFor('username'))
        {{ getErrorFor('username') }}
      @endif

routes.js

'use strict'
/** @type {typeof import('@adonisjs/framework/src/Route/Manager')} */
const Route = use('Route');
const User = use('App/Models/User');
const { validate } = use('Validator');

Route.on('/').render('welcome');
Route.post('/users', async ({ request, session, response }) => {

  const rules = { username: 'required' }
  const validation =  await validate(request.all(), rules)

  if (validation.fails()) {
    session.withErrors(validation.messages()).flashAll()
    return response.redirect('back')
  }else{
    var uname = request.collect(['username']);
    var u = await User.query().where({"username":uname}).fetch();
    var json = u.toJSON();
    session.put("user", json);
    return response.location('/listUserInfo');
  }
})

Route.get('/listUserInfo', ({session})=>{
  var userInfoJson = session.get("user", "d*");

  if (userInfoJson =="d*") {
    "error";
  } else {
    userInfoJson[0]['email'];
    userInfoJson[0]['id'];
  }
})

In /users I get a “Converting circular structure to JSON” error. I am assuming it is from the

var u = await User.query().where({"username":uname}).fetch();
var json = u.toJSON();

but it worked fine in adonis repl so i’m not sure what is wrong.
Any ideas?


#2

According to docs, right here: https://adonisjs.com/docs/4.0/response#_basic_example

You need to do the following

  • Inside you method use the response object as a parameter of it

async fetchAll({ response }){
      const u = await User.query().where({"username":uname}).fetch();
      return response.send(u)
}

  • After make a return of response object passing as a parameter the const name, in this case u

The final result should looks like this

image

As you can see the request is a json format

  • Optionally you can use response.json() getting the same result as the previous example

#3

What’s wrong with what i had? I believe its the same as what is written in https://adonisjs.com/docs/4.1/serializers#_introduction