首页 > 解决方案 > 如何在 JSON 响应中包含来自 MongoDB 的 ObjectID 键?

问题描述

在 MongoDB FindOne() 函数之后,我需要获取 ObjectID 并在 http.ResponseWriter 中使用它

    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)

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

谢谢

标签: go

解决方案


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

ID: bson.ObjectId("112233"),

我需要知道如何使用 DB 对象


推荐阅读