如果数组包含匹配值,则查找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.

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)