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

Mongodb 如果数组包含匹配值,则查找mgo文档,mongodb,go,mgo,Mongodb,Go,Mgo,我的API中有以下函数,用于检查用户是否拥有相关文档 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"

我的API中有以下函数,用于检查用户是否拥有相关文档

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
}

然而,它返回一个打印“未找到”的错误,尽管给了它两个ID,当我检查给定用户的艺术家ID列表时,它们肯定存在并且是相关的

也许我错了,但是
Id
被定义为
bson.ObjectId
,您将其作为字符串查询。试着替换

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


也许我错了,但是
Id
被定义为
bson.ObjectId
,您将其作为字符串查询。试着替换

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