I am trying to connect to remote mongodb server in golang and adding data in database. Its giving me error as follows: server returned error on SASL authentication step: Authentication failed.
Code:
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
// "os"
)
type Person struct {
Name string
Phone string
}
func main() {
session, err := mgo.Dial("mongodb://<dbuser>:<dbpassword>@ds041154.mongolab.com:41154/location")
if err != nil {
fmt.Println(err)
} else {
fmt.Println("Session created")
}
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("location").C("people")
err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
&Person{"Cla", "+55 53 8402 8510"})
if err != nil {
log.Fatal(err)
}
result := Person{}
err = c.Find(bson.M{"name": "Ale"}).One(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println("Phone:", result.Phone)
}
Any help on this is appreciated.
MongoDB can be managed remotely or connected to a separate application server by making a few changes to the default configuration. First, we'll install the MongoDB using the docker container, then configure the MongoDB installation to access from a trusted remote machine securely.
Your connection from client to server is blocked by firewall or network configuration. A MongoDB server is not listening on the requested Host/IP and port (check they are both correct) You are connecting to a remote MongoDB deployment that is not listening to the public IP you are connecting to.
Short answer. Login to your machine, open mongodb configuration file located at /etc/mongod. conf and change the bindIp field to your machine ip address (it is the same ip address which you are using to ssh to your machine), after that restart mongodb server.
an host Alias could be jamming access to 127.0. 0.1; If you are on Ubuntu (or any other linux distro) try opening /etc/hosts and see if there is any Alias for 127.0. 0.1 and comment it out. Save the host file, restart your computer and try starting the mongod service again (sudo systemctl start mongod).
I was getting similar error, but I found that I had entered wrong login credentials.
This code worked for me:
package main
import (
"fmt"
"time"
"gopkg.in/mgo.v2"
)
//const MongoDb details
const (
hosts = "ds026491.mongolab.com:26491"
database = "messagingdb"
username = "admin"
password = "youPassword"
collection = "messages"
)
func main() {
info := &mgo.DialInfo{
Addrs: []string{hosts},
Timeout: 60 * time.Second,
Database: database,
Username: username,
Password: password,
}
session, err1 := mgo.DialWithInfo(info)
if err1 != nil {
panic(err1)
}
col := session.DB(database).C(collection)
count, err2 := col.Count()
if err2 != nil {
panic(err2)
}
fmt.Println(fmt.Sprintf("Messages count: %d", count))
}
It is also on Github
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With