将* string类型转换为bson.ObjectId类型

i need to convert type string to bson.ObjectId, this is my current code :

type CampaignUpdateBody struct {
    CampaignName  *string    `json:"campaign_name" bson:"campaign_name"`
    FromName     []string    `json:"from_name" bson:"from_name"`
    FromEmail     *string    `json:"from_email" bson:"from_email"`
    ReplyEmail    *string    `json:"reply_email" bson:"reply_email"`
    Subject      []string    `json:"subject" bson:"subject"`
    BodyText      *string    `json:"body_text" bson:"body_text"`
    BodyHTML      *string    `json:"body_html" bson:"body_html"`
    SmtpList      *string    `json:"smtp_list_id" bson:"smtp_list"`
    EmailList     *string    `json:"email_list_id" bson:"email_list"`
}

// LetterTemplateUpdate updates some fields of the letter template.
func (s *Service) CampaignUpdate(c *gin.Context) {
    id := bson.ObjectIdHex(c.Param("id"))
    if !id.Valid() {
        c.JSON(http.StatusBadRequest, gin.H{"error": "id has wrong format"})
        return
    }

    var body CampaignUpdateBody
    if err := c.BindJSON(&body); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    token := c.MustGet(tokenKey).(*models.Token)

    params := storage.CampaignUpdateParams{}
    params.ID = id
    //..........................
    params.BodyText  = body.BodyText
    params.BodyHTML  = body.BodyHTML
    params.SmtpList  = body.SmtpList
    params.EmailList = body.EmailList

    stor := c.MustGet(storageKey).(storage.Storage)
    if err := stor.CampaignUpdate(token.UserID, params); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, gin.H{})
}

and this is my current error :

..\httpservice\campaigns.go:134:19: cannot use body.SmtpList (type *string) as t
ype bson.ObjectId in assignment
..\httpservice\campaigns.go:135:19: cannot use body.EmailList (type *string) as
type bson.ObjectId in assignment

i need convert body.SmtpList type as *string in bson.ObjectId , how i can do this ?

1个回答



根据文档, bson.ObjectId </ code>定义为</ p>

 类型ObjectId字符串
</ code> </ pre>

鉴于此,您应该能够使用</ p>

  params.SmtpList  = bson.ObjectId(* body.SmtpList)
</ code> </ pre>

这是类型转换,因为 ObjectId </ code>的基础类型是 string </ code>。</ p>

请注意,在执行此操作之前,请确保 body.SmtpList </ code>不是 nil </ code> 否则您的代码会崩溃。</ p>
</ div>

展开原文

原文

According to the documentation, bson.ObjectId is defined as

type ObjectId string

Given that, you should be able to use

params.SmtpList = bson.ObjectId(*body.SmtpList)

That's a type conversion, which works because the underlying type of ObjectId is string.

Note that you need to make sure that body.SmtpList isn't nil before doing this or your code will panic.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐