首页 > 解决方案 > HasMany relation not working in Adonis framework using mongodb database

问题描述

In my case, hasMany relation not working database like

Users.js

{
    "_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.js

{
    "_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 on USERS model

User.js

  /** 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"
            ],
            "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

标签: node.jsmongodbadonis.js

解决方案


尝试更改您的User模型,例如:

...
contacts() {
    return this.hasMany('App/Models/Contact', '_id', 'contact_ids')
}
...

推荐阅读