duyluonglc / lucid-mongo

Mongodb ODM for adonis framework
325 stars 61 forks source link

HasMany relation not working in Adonis framework using mongodb database #231

Open vikas-ukani opened 5 years ago

vikas-ukani commented 5 years ago

In my case, hasMany relation not working database like

Users table

{
    "_id" : ObjectId("5dc5617ac22c2921fc32b1f0"),
    "name" : "vikas",
    "email" : "vikas@gmail.com",
    "contact_ids" : [ 
        "5dc5572ee6143821e43ece31"
    ],

    "created_at" : ISODate("2019-11-08T12:37:12.452Z"),
    "updated_at" : ISODate("2019-11-08T12:37:12.456Z")
}

Contact Table

{
    "_id" : ObjectId("5dc5572ee6143821e43ece31"),
    "name" : "vikas Contacts",
    "mobile" : 95754681658,
    "user_id" : "5dc5617ac22c2921fc32b1f0",
    "created_at" : ISODate("2019-11-08T11:53:15.781Z"),
    "updated_at" : ISODate("2019-11-08T11:53:15.786Z")
}

And, I'm applying relation to USERS model

User.js // model

  // get many contacts  
contacts() {
    return this.belongsToMany('App/Models/Contact', '_id', 'contact_ids')
    // hasMany(relatedModel, primaryKey, foreignKey)
  }

And, The final result is // OUTPUT

{
            "_id": "5dc5617ac22c2921fc32b1f0",
            "name": "vikas",
            "email": "vikas@gmail.com",
            "contact_ids": [
                "5dc5572ee6143821e43ece31"
            ],
            "password": "$2a$10$jiSfRAqDWlHv8yie3VBm3eWo.flT09xiOq8vORtSlwKvrJTM5qqPy",
            "created_at": "2019-11-08T12:37:12.452Z",
            "updated_at": "2019-11-08T12:37:12.456Z",
            "contacts": []
        }

When, I applying has many relations it doesn't show contacts list in an array

duyluonglc commented 5 years ago

@vikas-ukani try

const class User extends Model {
  contacts() {
    return this.hasMany('App/Models/Contact')
  }
}

const class Contact extends Model {
  static get objectIds () { return ['_id', 'user_id'] }
  user() {
    return this.belongsTo('App/Models/User')
  }
}

and remove contact_ids field make sure your user_id field in contacts collection is stored as objectid

golinmarq commented 4 years ago

@vikas-ukani try

const class User extends Model {
  contacts() {
    return this.hasMany('App/Models/Contact')
  }
}

const class Contact extends Model {
  static get objectIds () { return ['_id', 'user_id'] }
  user() {
    return this.belongsTo('App/Models/User')
  }
}

and remove contact_ids field make sure your user_id field in contacts collection is stored as objectid

I did this but it doesn't work 🙁