Home > database >  Go/Mongo: Returning a single object
Go/Mongo: Returning a single object

Time:03-15

The trouble I've been having is that the code bellow only works if the token isn't in an array, (or is considered the original refresh token the rest descend from). I'm wasting so much precious energy trying to find a way to return the correct session.

// Find the current sessions info
currentSession := model.Session{}
lookupSession := bson.D{{Key: "token", Value: refreshToken}}
_ := tokensCol.FindOne(ctx, lookupSession).Decode(&currentSession)
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDcyMzAxNTJ9.R-Tm8sgs..."
userID: "1"
userAgent: ""
ip: ""
exp: 1647230152
valid: false
original: true
family:
   0:
      token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDcyMzAyNTJ9.noqkeUYW..."
      userID: "1"
      userAgent: ""
      ip: ""
      exp: 1647230252
      valid: true
      original: false

Is there a one stop shop for returning the object the token resides either at the top-level of the document or nested within the family array? The code bellow partially works, but returns the entire document starting with the original token. Not sure how to shape the data retrieved

currentSession := model.Session{}
filter := bson.M{
    "family": bson.M{
        "$elemMatch": bson.M{"token": refreshToken},
    },
}
_ = tokensCol.FindOne(ctx, filter).Decode(&currentSession)

fmt.Println(currentSession)

Returns:

{c8ncjdiaas68dh9fq1d0 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDcyMzcwNjJ9.KlR1mdC0UBnGfxr31MZwzoE7tTVQwuN5uciteSqh8Kg 1 1647237062 false true [{c8ncjhaaas68dh9fq1dg eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDcyMzcwNzd9.lx6MIBN_pzlKei9DWr0-k-kvr6yLJ4XfhGSTNNVqRKY 1 1647237077 true false []}]}

I've tried plenty that I won't bother adding onto this cluster of a question, I apologize ahead of time but really need a better glimpse?

CodePudding user response:

So basically you want to find a document that has a token field OR an element in the family array that has a token field with a given value? That's simply an $or condition, so use this lookupSession filter document:

lookupSession := bson.M{
    "$or": []bson.M{
        {"token": refreshToken},
        {"family.token": refreshToken},
    },
}

If you don't want to retrieve the complete result document, use projection. For an example, see How to filter fields from a mongo document with the official mongo-go-driver

  • Related