Fetch data and related foreign key related object


Hello, I have set up a database with mongo, and I’m using Lucid to fetch data from DB.
I have two collections:

  • questions
  • sections

Basically every question has one (belongs to) a section, so this is the mongo-db situation:

Every question points to a mongodb document via section_id. As of now, I am only able to fetch such id, but I am not able show an output like this:

	"_id": ObjectId("5c1a24d42c58d34c58460772"),
	"slug": "company-roles",
	"copy": {
		"title": "Are you OK?",
		"subtitle": "Health check"
	"category": "SimpleQuestion",
	"section": {
		"_id": ObjectId("5c1a24d42c58d34c5846075d"),
		"description": "my category"

So I defined these two models:


'use strict'

/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
const Model = use('Model')

class Question extends Model {
        return this.hasOne('App/Models/Section')

module.exports = Question


'use strict'

/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
const Model = use('Model')

class Section extends Model {

module.exports = Section

Then, I’m trying to load both Question and Section like this:

const question = await Question.findBy({ _id})
const section = await question.section().fetch()

The problem here is that my section document is not fetched. Why?



with(‘section’ ) ?


considering he’s working with mongo a non relational database I ask to you: with method will work?


Thank you guys for fast replying! :slight_smile:

I think I solved this way:

const question = await Question.findBy({ my_question_id})
const _id = question.section_id
const section = await Section.findBy({ _id })

I noticed there is no need to define any relation in both models (Question and Section), since this is a data fetch only (I used a pre-population script to insert data in mongo). At this point I just have a doubt if those relationships declarations in models are necessary or not.