Uploaded image for project: 'Go Driver'
  1. Go Driver
  2. GODRIVER-1294

Collection.InsertOne is having problems with a struct that has a interface as attribute

    XMLWordPrintable

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Major - P3
    • Resolution: Fixed
    • Affects Version/s: 1.1.0
    • Fix Version/s: 1.2.0
    • Component/s: BSON
    • Labels:
    • Environment:
      Development

      Description

      I'm having problems when I try to save a struct with a interface property

      package main
       
      import (
      	"context"
      	"log"
      	"time"
      )
       
      const MAX_INSERT_TIMEOUT = time.Second * 10
       
      type Scannable interface {
      	GetValue() int
      	IsOpen() bool
      }
       
      type Port struct {
      	Value int  `bson:"value"`
      	Open  bool `bson:"open"`
      }
       
      type MongoDBPort struct {
      	Port `bson:",inline"`
      }
       
      type Scanner struct {
      	Value       string      `bson:"value"`
      	Scannables  []Scannable `bson:"scannable"`
      	Parallelism int         `bson:"-"`
      }
       
      func NewPort(n int) Scannable {
      	if n == 27017 {
      		return &MongoDBPort{
      			Port{
      				Value: n,
      			},
      		}
      	}
       
      	return &Port{
      		Value: n,
      	}
      }
       
      func (p Port) IsOpen() bool {
      	return p.Open
      }
       
      func (p Port) GetValue() int {
      	return p.Value
      }
       
      func (s *Scanner) Save(ctx context.Context) {
      	var err error
       
      	db := Get("issues")
       
      	col := db.Collection("scanners")
       
      	ctxt, cancel := context.WithTimeout(ctx, MAX_INSERT_TIMEOUT)
      	defer cancel()
       
      	_, err = col.InsertOne(ctxt, s)
       
      	if err != nil {
      		log.Printf("Error on insert. %s", err.Error())
      		return
      	}
       
      	log.Println("Saved!")
      }
      

      This is the output when I try to save a Scanner:

      Error on insert. no encoder found for main.Scannable
      

      I found a solution. But, in my opinion, is not the best solution. I used "gopkg.in/mgo.v2/bson" package for marshalling the object and It is working fine. I tried with "go.mongodb.org/mongo-driver/bson" package but the error persist.

      o, err := bson.Marshal(s)
       
      if err != nil {
        log.Printf("Error on marshal. %s", err.Error())
        return
      }
       
      _, err = col.InsertOne(ctxt, o)
      

        Attachments

          Activity

            People

            Assignee:
            isabella.siu Isabella Siu (Inactive)
            Reporter:
            davidbayo10@gmail.com David Bayo Alcaide
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: