Lucid Model Relationship on MongoDB


#1

Hello,

I have two Models on my AdonisJS application like:
User:

'use strict'

/** @type {typeof import('lucid-mongo/src/LucidMongo/Model')} */
const Model = use('Model')

class User extends Model {

  cart() {
    return this.hasMany('App/Models/Cart')
  }
}

module.exports = User

Cart:

'use strict'

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

class Cart extends Model {
}

module.exports = Cart

I want to insert an User into users MongoDB collection and one associated Cart into the carts collection.
I do this as it follows after creating the new User():

await user.cart().save(cart);

The user is created as expected and I also have a Cart into the cart collection.
If I query the users collection by the ID or the username, I see the associated cart.

My question is: why if I try to delete the newly created user via MongoDB client query, I can do this without any problem? I mean, why it doesn’t raise any “foreign key” error? Did I create the user the wrong way on NodeJS?


#2

Lucid only supports SQL databases, I am not sure how you have been able to save user in MongoDB at first place


#3

Hi! I used this one: lucid-mongo.


#4

Does MongoDB has foreign key constraints?


#5

I am not so expert on MongoDB but I used the lucid-mongo ORM that is creating collections and entities automatically.
This is a good point actually, because it’s actually something I wanted to achieve. Namely, every time I create a new User and it is stored into the DB, I also want a “carts” property containing one or more carts.

For this reason I changed a bit the User model as it follows:

'use strict'

/** @type {typeof import('lucid-mongo/src/LucidMongo/Model')} */
const Model = use('Model')

class User extends Model {

  carts() {
    return this.hasMany('App/Models/Cart')
  }
}

module.exports = User

Now I just execute the following to save the user and its cart:

await user.carts().save(cart);

If I see the mongoDB carts collection it contains the new cart which is also visible in the User Detail


#6

since MongoDB is a flexible schema, does not implement at least in the common sense the foreign key constraints