多个帐户的嵌套关联

时间:2017-09-06 14:08:44

标签: javascript mongodb mongoose model-associations

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

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.?。还不确定我是否应该使用嵌入式 vs 对象引用以及适当的位置。我试图让这些协会匹配起来。

1 个答案:

答案 0 :(得分:2)

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

以下是一个快速建议:

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