我一直在尝试连接到 mongodb atlas,但出现以下错误。
auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AtlasError) bad auth : Authentication failed.
我还在 at mongodb atlas GUI 上将我的 IP 列入白名单...
URI 链接适用于 1.0 及更高版本的 go 应用程序
以下是我的代码
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
// Name of the database.
DBName = "Stats"
// Name of the collections
notesCollection = "notes"
URI = "mongodb+srv://<username><password>@inshorts.0wwoh.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
)
type Note struct {
ID primitive.ObjectID `bson:"_id" json:"id,omitempty"`
Title string `json:"title"`
Body string `json:"body"`
CreatedAt time.Time `bson:"created_at" json:"created_at,omitempty"`
UpdatedAt time.Time `bson:"updated_at" json:"updated_at,omitempty"`
}
func main() {
ctx := context.Background()
// Options to the database.
clientOpts := options.Client().ApplyURI(URI)
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
fmt.Println(err)
return
}
db := client.Database(DBName)
coll := db.Collection(notesCollection)
fmt.Println(coll.Name()) // output: notes
note := Note{}
// An ID for MongoDB.
note.ID = primitive.NewObjectID()
note.Title = "First note"
note.Body = "Some spam text"
note.CreatedAt = time.Now()
note.UpdatedAt = time.Now()
result, err := coll.InsertOne(ctx, note)
if err != nil {
fmt.Println(err)
return
}
// ID of the inserted document.
objectID := result.InsertedID.(primitive.ObjectID)
fmt.Println(objectID)
}
我使用 atlas 是因为我在系统中安装 MongoDB 时遇到问题(我遵循此 https://stackoverflow.com/a/67719154/14409588
),每当我运行 sudo apt-get install -y mongodb-org
时,我都会收到以下错误
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
mongodb-database-tools mongodb-mongosh mongodb-org-database
mongodb-org-database-tools-extra mongodb-org-mongos mongodb-org-server
mongodb-org-shell mongodb-org-tools
The following NEW packages will be installed
mongodb-database-tools mongodb-mongosh mongodb-org mongodb-org-database
mongodb-org-database-tools-extra mongodb-org-mongos mongodb-org-server
mongodb-org-shell mongodb-org-tools
0 to upgrade, 9 to newly install, 0 to remove and 25 not to upgrade.
Need to get 0 B/144 MB of archives.
After this operation, 436 MB of additional disk space will be used.
dpkg: unrecoverable fatal error, aborting:
unknown system user 'mongodb' in statoverride file; the system user got removed
before the override, which is most probably a packaging bug, to recover you
can remove the override manually with dpkg-statoverride
E: Sub-process /usr/bin/dpkg returned an error code (2)
因此,由于我无法安装 mongo,因此我无法通过终端检查 URI 是否确实有效,但我很确定 URI 是正确的,因为它是从 atlas gui 本身复制的