인터페이스를 사용하여 mgo를 사용하여 MongoDB에서 다양한 유형의 임베디드 노드를 모델링하는 방법은 무엇입니까?

DDD
풀어 주다: 2024-10-26 10:34:29
원래의
769명이 탐색했습니다.

How to Model Embedded Nodes of Different Types in MongoDB with mgo using Interfaces?

mgo(Go)에서 모델로 사용되는 인터페이스 유형

문제:

시나리오에서 다양한 유형의 워크플로우 및 내장 노드와 관련된 MongoDB의 노드 모델링 인터페이스를 mgo와 함께 사용하면 오류가 발생합니다. mgo가 유형 정보 없이 포함된 Node 문서를 역마샬링할 수 없기 때문에 오류가 발생합니다.

해결 방법:

이 제한을 극복하려면 Node 유형을 모두 보유하는 구조체를 정의하는 것이 좋습니다. 및 관련 유형 정보:

<code class="go">type NodeWithType struct {
   Node Node `bson:"-"`
   Type string
}</code>
로그인 후 복사

Workflow 구조체 내에서 NodeWithType 구조체 배열을 사용하여 노드를 저장합니다.

<code class="go">type Workflow struct {
   CreatedAt time.Time
   StartedAt time.Time
   CreatedBy string
   Nodes []NodeWithType
}</code>
로그인 후 복사

데이터를 올바르게 디코딩하려면 SetBSON 함수를 구현합니다. on NodeWithType:

<code class="go">func (nt *NodeWithType) SetBSON(r bson.Raw) error {
   // Decode the type string
   typeStr := r.String()

   // Create a new Node value based on the type string
   switch typeStr {
   case "EmailNode":
      nt.Node = &EmailNode{}
   case "TwitterNode":
      nt.Node = &TwitterNode{}
   default:
      return errors.New("Unknown node type")
   }

   // Unmarshal the remaining data to the Node value
   bsonBytes, err := bson.Marshal(r.Body)
   if err != nil {
      return err
   }
   return bson.Unmarshal(bsonBytes, nt.Node)
}</code>
로그인 후 복사

이 접근 방식을 사용하면 mgo는 NodeWithType 구조체에 저장된 유형 정보를 기반으로 포함된 노드를 올바르게 역마샬링할 수 있습니다.

위 내용은 인터페이스를 사용하여 mgo를 사용하여 MongoDB에서 다양한 유형의 임베디드 노드를 모델링하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!