[GODRIVER-1294] Collection.InsertOne is having problems with a struct that has a interface as attribute Created: 03/Sep/19  Updated: 28/Oct/23  Resolved: 07/Nov/19

Status: Closed
Project: Go Driver
Component/s: BSON
Affects Version/s: 1.1.0
Fix Version/s: 1.2.0

Type: Improvement Priority: Major - P3
Reporter: David Bayo Alcaide Assignee: Isabella Siu (Inactive)
Resolution: Fixed Votes: 0
Labels: mgocompat
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
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)



 Comments   
Comment by Githook User [ 07/Nov/19 ]

Author:

{'name': 'iwysiu', 'username': 'iwysiu', 'email': 'isabella.siu@10gen.com'}

Message: GODRIVER-1294 support marshaling interfaces to bson (#206)
Branch: master
https://github.com/mongodb/mongo-go-driver/commit/85a8e363c138e7c405976deb9816c72efe54f7b4

Comment by Isabella Siu (Inactive) [ 23/Sep/19 ]

Hi davidbayo10@gmail.com,

We are currently working on a project to create an mgo compatible BSON registry to solve this and other similar problems.

Generated at Thu Feb 08 08:36:06 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.