dongzuozhu66776 2016-02-21 15:33
浏览 44
已采纳

如果数组包含匹配值,则查找mgo文档

I have the following function in my API in order to check a user owns a related document

type User struct {
    Id          bson.ObjectId   `bson:"_id,omitempty" json:"id"`
    Name        string          `form:"name" bson:"name,omitempty" json:"name,omitempty"`
    Password    string          `form:"password" bson:"password,omitempty" json:"-" binding:"required"`
    Email       string          `form:"email" bson:"email,omitempty" json:"email" binding:"required"`
    Artists     []bson.ObjectId `form:"artists" bson:"artists,omitempty" json:"artists" inline`
    ContentFeed []bson.ObjectId `form:"content_feed" bson:"content_feed,omitempty" json:"content_feed" inline`
    Location    string          `form:"user_location" bson:"user_location,omitempty" json:"user_location,omitempty"`
    TopTracks   []bson.ObjectId `form:"top_tracks" bson:"top_tracks" json:"top_tracks" inline`
    Avatar      string          `form:"avatar" bson:"avatar,omitempty" json:"avatar,omitempty"`
    BgImg       string          `form:"bg_img" bson:"bg_img,omitempty" json:"bg_img,omitempty"`
}

// Get artist
// This doesn't actual get the full artist object, this just checks that
// the artist id given is stores against the given users list of artists
func (repo *UserRepo) GetArtist(user string, artist string) (bool, error) {
    userData := &User{}
    fmt.Println(user)
    err := repo.collection.Find(bson.M{"_id": user, "artists": bson.M{"$in": []bson.ObjectId{bson.ObjectIdHex(artist)}}}).One(&userData)

    if err != nil {
        fmt.Println(err)
        return false, err
    }

    return true, err
}

However it returns an error which prints 'not found', despite giving it two ID's which definitely exist and are related when I inspect the list of artist id's for that given user.

  • 写回答

1条回答 默认 最新

  • dongyin2643 2016-02-21 17:31
    关注

    Maybe I'm wrong but Id is defined as bson.ObjectId and you are querying it as string. Try to replace

    err := repo.collection.Find(bson.M{"_id": user, "artists": bson.M{"$in": []bson.ObjectId{bson.ObjectIdHex(artist)}}}).One(&userData)
    

    with

    err := repo.collection.Find(bson.M{"_id": bson.ObjectIdHex(user), "artists": bson.M{"$in": []bson.ObjectId{bson.ObjectIdHex(artist)}}}).One(&userData)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料