Golang MongoDB错误:结果参数必须是切片地址 -(数组)

huangapple go评论72阅读模式
英文:

Golang MongoDB Error: result argument must be a slice address - (Arrays)

问题

我想从Mongo集合中检索ID列表(类型为long)。

ids := []int64
如果count >= 5 {
err = collection.Find(query).Select(bson.M{
"_id": 1
}).Skip(rand.Intn(count - 4)).Limit(4).All(ids)
}

我收到一个错误,错误信息是http: panic serving [::1]:62322: result argument must be a slice address。

我尝试使用make来获取切片,但结果出现了相同的错误。

ids := make([]int64, 0, 4)
如果count >= 5 {
err = collection.Find(query).Select(bson.M{
"_id": 1
}).Skip(rand.Intn(count - 4)).Limit(4).All(ids)
}

英文:

I want to retrieve list of ids (type long) from the mongo collection

ids: = [] int64
if count >= 5 {
  err = collection.Find(query).Select(bson.M {
    "_id": 1
  }).Skip(rand.Intn(count - 4)).Limit(4).All(ids)
}

I get an error stating http: panic serving [::1]:62322: result argument must be a slice address

I tried using make for getting the slice, which resulted in the same error

ids: = make([]int64, 0, 4)
if count >= 5 {
  err = collection.Find(query).Select(bson.M {
    "_id": 1
  }).Skip(rand.Intn(count - 4)).Limit(4).All(ids)
}

答案1

得分: 4

将切片的指针传递给All函数:

ids := []int64
if count >= 5 {
  err = collection.Find(query).
      Select(bson.M{"_id": 1}).
      Skip(rand.Intn(count - 4)).
      Limit(4).
      All(&ids)  // <-- 修改在这里
}
英文:

Pass a pointer to the slice to All:

ids: = []int64
if count &gt;= 5 {
  err = collection.Find(query).
      Select(bson.M{&quot;_id&quot;: 1}).
      Skip(rand.Intn(count - 4)).
      Limit(4).
      All(&amp;ids)  // &lt;-- change is here
}

huangapple
  • 本文由 发表于 2017年5月25日 15:55:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/44175265.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定