2016-02-21 2 views
0

У меня есть следующие функции в моем 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 
} 

Однако она возвращает ошибку, которая печатает «не найдено», несмотря на отказ это два идентификатора, которые определенно существуют и связаны, когда я проверяю список идентификаторов исполнителя для данного пользователя.

ответ

2

Возможно, я ошибаюсь, но Id определяется как bson.ObjectId, и вы запрашиваете его как строку. Попробуйте заменить

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

с

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

ахам !! Хорошее место! Спасибо, это сделало работу –

Смежные вопросы