【问题标题】:datastore doesn't put nested struct in Go数据存储不会将嵌套结构放入 Go
【发布时间】:2017-12-12 23:39:57
【问题描述】:

结构如下所示:

type Account struct {
  Username         string    // NameKey
  Password         []byte    `datastore:",noindex"`
  RegistrationTime time.Time `datastore:",noindex"`
  AppUser
}

type AppUser struct {
  LoginEntries []LoginEntry `datastore:",noindex"`
}

type LoginEntry struct {
  Timestamp time.Time `datastore:",noindex"`
  UserAgent string    `datastore:",noindex"`
  IP        string    `datastore:",noindex"`
}

我也确定我正确放置了数据,因为其他数据更新没有问题,我在将其保存到数据存储区 (Put(ctx, key, &account) 之前尝试fmt.Println account Account 的内容,当我打印它然后我可以看到所有AppUser 信息.. 但是当我稍后Get 用户时AppUser 信息不存在(只显示为{[]})。

我很确定我之前在数据存储中存储了嵌套的结构切片没有任何问题,所以我很困惑可能是什么原因造成的......


Put 函数:

func PutAccount(ctx context.Context, acc Account) (*datastore.Key, error) {
  if isValidUsername(acc.Username) != true {
    return nil, errors.New("Invalid username.")
  }
  var hashedPassword []byte
  if acc.RegistrationTime.IsZero() {
    var err error
    hashedPassword, err = bcrypt.GenerateFromPassword(acc.Password, 12)
    if err != nil {
      return nil, err
    }
  } else {
    hashedPassword = acc.Password
  }
  account := Account{
    Username:         strings.ToLower(acc.Username),
    Password:         hashedPassword,
    RegistrationTime: time.Now(),
    AppUser:          acc.AppUser}
  fmt.Println("PutAccount, account:", account) // before saving it prints the AppUser without problems
  key := datastore.NameKey("Account", account.Username, nil)
  return database.DatastoreClient().Put(ctx, key, &account)
}

获取函数:

func GetAccount(ctx context.Context, key *datastore.Key) (Account, error) {
  var account Account
  err := database.DatastoreClient().Get(ctx, key, &account)
  if err != nil {
    return account, err
  }
  return account, nil
}

【问题讨论】:

  • 请显示用于获取和放置数据的代码。您可能还想为您的 Get 尝试一个平面结构,看看它是否有效。
  • @Marc 请参阅编辑。我也注意到了这个答案,但我发现文档非常混乱和复杂
  • 我的意思是你需要弄清楚哪里出了问题。是put还是get?您可以通过移动到一个平面结构来缩小问题范围,其中LoginEntriesAccount 的一个字段。使用其他工具检查数据是否确实存在也会有所帮助。
  • 嵌入式结构被展平。详情见:Datastore: Structured Properties

标签: go google-cloud-datastore


【解决方案1】:

使用命名结构有效。例如:

type Account struct {
  Username         string    // NameKey
  Password         []byte    `datastore:",noindex"`
  RegistrationTime time.Time `datastore:",noindex"`
  AppUser          AppUser
}

至于为什么匿名嵌入式结构不这样做,这可能值得issue

【讨论】:

  • 非常感谢,非常感谢
  • 如果它被命名,它并不是真正的“嵌入”,现在是吗? ;)
猜你喜欢
  • 1970-01-01
  • 2013-06-13
  • 1970-01-01
  • 2021-11-24
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 1970-01-01
相关资源
最近更新 更多