douzhenchun6782 2019-01-27 00:24
浏览 947
已采纳

将* 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条回答

  • dongtuo4723 2019-01-27 02:23
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能