【问题标题】:$push string as an array in mongo document$push 字符串作为 mongo 文档中的数组
【发布时间】:2021-08-17 14:59:18
【问题描述】:

我无法理解 Go 中的数组,尤其是同时使用 graphql 和 mongo。有了 JS,这一切对我来说都是轻而易举的事,但我想知道你是否可以看看我所拥有的并指出显而易见的事情!

我正在寻找一个形状如下的对象:

time
├── login
│   ├── 0
│   │   └── "2021-08-16T20:11:54-07:00"
│   ├── 1
│   │   └── "2021-08-16T20:11:54-07:00"
│   └── 2
        └── "2021-08-16T20:11:54-07:00"

models.go:

type Time struct {
    Login []string
}

type User struct {
    ID       graphql.ID
    Time     Time
}

schema.graphql:

type Time {
  login: [String!]!
}

type User {
  id:      ID!
  time:    Time!
}

database.go:

filter := bson.D{{Key: "email", Value: email}}
arr := [1]string{time.Now().Format(time.RFC3339)}
update := bson.D{
  {Key: "$push", Value: bson.D{
    {Key: "time.login", Value: arr},
  }},
}
result, err := collection.UpdateOne(ctx, filter, update)

我也试过了:

update := bson.D{
  {Key: "$push", Value: bson.D{
    {Key: "time.login", Value: time.Now().Format(time.RFC3339)},
  }},
}
result, err := collection.UpdateOne(ctx, filter, update)

但总是以同样的错误告终:

error="write exception: write errors: [The field 'time.login' must be an array but is of type null in document {_id: ObjectId('611b28fabffe7f3694bc86dc')}]"

【问题讨论】:

    标签: mongodb go graphql-go


    【解决方案1】:

    [1]string{} 是一个数组。 []string{} 是一个切片。两者是不同的。数组是固定大小的对象。切片可以动态增长/收缩。

    在这种情况下,你不应该使用任何一个,因为$push 得到一个值,而不是一个切片:

    update := bson.D{
      {Key: "$push", Value: bson.D{
        {Key: "time.login", Value: time.Now().Format(time.RFC3339)},
      }},
    }
    

    【讨论】:

    • 这是我首先尝试过的,但我遇到了同样的错误!
    • 这意味着您已经插入了带有time.login:null 的文档。插入不带时间字段的文档。使用 bson omitempty 标签。
    【解决方案2】:

    尝试初始化切片。 并使用追加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      相关资源
      最近更新 更多