如何在 JSON 响应中包含来自 MongoDB 的 ObjectID 密钥?



在MongoDB FindOne((函数之后,我需要获取ObjectID并在http中使用它。响应编写器

documento, err := bd.IntentoLogin(t.Email, t.Password)
if err != nil {
http.Error(w, "Usuario y/o Contraseña inválidos", 400)
return
}
jwtKey, err := jwt.GeneroJWT(t.Email)
if err != nil {
http.Error(w, "Ocurrió un error al intentar generar el Token correspondiente. "+err.Error(), 400)
return
}
resp := models.RespuestaLogin{
____________________________________      
<<<<< Here I need to Include the ObjectID
____________________________________
Nombre: documento.Nombre,
Apellidos: documento.Apellidos,
Token: jwtKey,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(resp)

如果我需要将此对象ID添加到JSON结构中,正确的语法是什么?

谢谢

type RespuestaLogin struct {
ID        bson.ObjectId `bson:"_id"`
Nombre    string        `bson:"nombre"`
Apellidos string        `bson:"apellidos"`
// rest of your fields...
}
resp := models.RespuestaLogin{
ID: bson.ObjectId("112233"),
Nombre: documento.Nombre,
Apellidos: documento.Apellidos,
Token: jwtKey,
}

您的函数db.IntentoLogin()必须返回一个字符串以作为 ObjectID 插入或适合ObjectId类型的内容。

谢谢,但在您的示例中,您使用了文字

ID:bson。ObjectId("112233"(,

我需要知道如何改用数据库对象

最新更新