【问题标题】:Nested associations for multiple accounts多个帐户的嵌套关联
【发布时间】:2017-09-06 14:08:44
【问题描述】:

我正在尝试将各种登录方法与mongo 中的同一User 模型相关联。

const UserSchema = new Schema({
  email: String
  isVerified: { default: false, type; Boolean }
  accounts: {
    ref: 'Account',
    type: Schema.Types.ObjectId
  }
})

const AccountSchema = new Schema({
  facebook: {
    ref: 'FacebookAccount',
    type: Schema.Types.?
  },
  local: {
    ref: 'LocalAccount',
    type: Schema.Types.?
  },
  twitter: {
    ref: 'TwitterAccount',
    type: Schema.Types.?
  },
})

const LocalAccount = new Schema({
  email: String,
  name: String,
  phone: String,
  password: String,
  _user: {
    ref: 'User',
    type: Schema.Types.ObjectId
  }
}) 

我希望返回给我的数据看起来像:

{
  _id: '12345789',
  email: 'turdFerguson@gmail.com',
  accounts: {
    facebook: { ... }
    local: { ... }
  }
}

我真的不确定这些关联,但个人帐户上的Schema.Types.?。也不确定我是否应该使用 embedded vs object 参考以及在哪里合适。我正在兜圈子,试图让关联匹配。

【问题讨论】:

  • 为什么不使用一个集合呢?这似乎有点矫枉过正。
  • @Mikey 实际上我从未考虑过。我想这是一个可行的想法。搜索用户是否存在,然后根据用于身份验证的登录方法将数据存储在相应的帐户中。我将对此进行调查,看看它是否适用于我想要完成的工作。谢谢你的想法。

标签: javascript mongodb mongoose model-associations


【解决方案1】:

我建议您使用嵌入式保持简单。

这是一个快速的建议:

const UserSchema = new Schema({
    isVerified: { 
        default: false, 
        type: Boolean 
    },
    accounts: {
        local: {
            email: String,
            name: String,
            phone: String,
            password: String
        },
        facebook: {
            // fields related to Facebook
        },
        twitter: {
            // fields related to Twitter
        }
    }
})

我删除了email,因为您已经拥有accounts.local.email,因此拥有它似乎是多余的

【讨论】:

  • 感谢您的建议,让工作变得轻松多了!
猜你喜欢
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 2014-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多