【问题标题】:MongoDB relations child to parentMongoDB关系子与父
【发布时间】:2019-03-31 23:06:24
【问题描述】:

我创建了一个 Meteor 应用程序,其中有两个集合,ActivityCards 和 Users。我在我的 ActivityCard 集合中有一个对 User 的引用,如下所示:

 {
    "_id" : "T9QwsHep3dMSRWNTK",
    "cardName" : "Guntnauna",
    "activitycardType" : 10,
    "startDate" : "1952-08-09",
    "remainingHours" : 0,
    "activities" : [ 
      {
        "activityName" : "Cfuw",
        "activityTotal" : "5",
        "activityEmployee" : "Smamnktl",
        "activityDate" : "1960-07-16"
      }, 

      ... 
    ],
    "customerID" : "z9hXczmWaf7wgdAtj",
    "isArchived" : 0
}

customerID 包含以下用户集合的 id:

{
    "_id" : "9mXAZkmfpKMPvQY8Y",
    "createdAt" : ISODate(),
    "services" : {
      "password" : {
        "bcrypt" : ""
      }
    },
    "emails" : [ 
      {
        "address" : "topony@mailinator.com",
        "verified" : false
      }
    ],
    "profile" : {
      "relationNumber" : "962",
      "companyName" : "Snider Kinney Co",
      "locationStreet" : "Ullamco eaque consequatur aspernatur consectetur eiusmod eligendi enim rerum consectetur asperiores officia eius itaque expedita dolorum",
      "locationPostal" : "Sit inventore asperiores est anim commodo non fugiat consequat Voluptatem tempore sunt culpa magni",
      "locationCity" : "Ipsum et fugit pariatur Nobis eveniet neque veniam perferendis eius ut quo excepteur consequatur voluptatem architecto",
      "contactName" : "Julian Moran",
      "contactPhone" : "+388-14-8339022",
      "isArchived" : 0
    },
    "roles" : {
      "customers" : [ 
        "customer"
      ]
    }
} 

我是 MongoDB 的新手,不知道这是否是正确配置的关系 在文档中,我主要找到从父级到子级的关系,而不是相反的关系。

我想知道你们对这种类型的关系有什么建议。 如何保存它们,从两个集合中获取数据等。

如果我的代码可以使用,我想知道如何获取从孩子到父母的关系并显示它们。目前我只使用了 MongoDB 中的 find() 方法,并将数据映射到单独的值中。

【问题讨论】:

    标签: javascript mongodb meteor collections


    【解决方案1】:

    你可以在你的 mongodb 集合中有这样的关系。如果您使用的是猫鼬,您可以像这样在您的架构中定义它们:

    customerId:{{ type: mongoose.Schema.ObjectId, ref: 'user' }}
    

    您可以使用mongoose populate 从孩子联系父母。 欲了解更多信息,请参阅

    https://mongoosejs.com/docs/populate.html

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    相关资源
    最近更新 更多