{"id":41384,"date":"2024-12-01T12:55:25","date_gmt":"2024-12-01T04:55:25","guid":{"rendered":"https:\/\/fwq.ai\/blog\/41384\/"},"modified":"2024-12-01T12:55:25","modified_gmt":"2024-12-01T04:55:25","slug":"golang%e6%97%a0%e6%b3%95%e5%9c%a8mongodb%e4%b8%ad%e5%88%9b%e5%bb%ba%e6%96%87%e6%a1%a3","status":"publish","type":"post","link":"https:\/\/fwq.ai\/blog\/41384\/","title":{"rendered":"Golang\u65e0\u6cd5\u5728MongoDB\u4e2d\u521b\u5efa\u6587\u6863"},"content":{"rendered":"<p><b><\/b> <\/p>\n<p>\u5f53\u524d\u4f4d\u7f6e\uff1a <span>&gt;<\/span>  <span>&gt;<\/span>  <span>&gt;<\/span>  <span>&gt;<\/span> <span>Golang\u65e0\u6cd5\u5728MongoDB\u4e2d\u521b\u5efa\u6587\u6863<\/span><\/p>\n<h1>Golang\u65e0\u6cd5\u5728MongoDB\u4e2d\u521b\u5efa\u6587\u6863<\/h1>\n<p><span>\u6765\u6e90\uff1astackoverflow<\/span><br \/>\n<span>2024-04-19 23:36:32<\/span><br \/>\n<span><i><\/i>0\u6d4f\u89c8<\/span><br \/>\n<span style=\"cursor: pointer\"><i><\/i>\u6536\u85cf<\/span> <\/p>\n<p>\u672c\u7bc7\u6587\u7ae0\u7ed9\u5927\u5bb6\u5206\u4eab\u300aGolang\u65e0\u6cd5\u5728MongoDB\u4e2d\u521b\u5efa\u6587\u6863\u300b\uff0c\u8986\u76d6\u4e86Golang\u7684\u5e38\u89c1\u57fa\u7840\u77e5\u8bc6\uff0c\u5176\u5b9e\u4e00\u4e2a\u8bed\u8a00\u7684\u5168\u90e8\u77e5\u8bc6\u70b9\u4e00\u7bc7\u6587\u7ae0\u662f\u4e0d\u53ef\u80fd\u8bf4\u5b8c\u7684\uff0c\u4f46\u5e0c\u671b\u901a\u8fc7\u8fd9\u4e9b\u95ee\u9898\uff0c\u8ba9\u8bfb\u8005\u5bf9\u81ea\u5df1\u7684\u638c\u63e1\u7a0b\u5ea6\u6709\u4e00\u5b9a\u7684\u8ba4\u8bc6(B \u6570)\uff0c\u4ece\u800c\u5f25\u8865\u81ea\u5df1\u7684\u4e0d\u8db3\uff0c\u66f4\u597d\u7684\u638c\u63e1\u5b83\u3002<\/p>\n<p> \u95ee\u9898\u5185\u5bb9<br \/>\n <\/p>\n<p>\u6211\u6b63\u5728\u5c1d\u8bd5\u5c06\u6587\u6863\u63d2\u5165 mongodb\uff0c\u4f46\u5c3d\u7ba1\u6210\u529f\u8fde\u63a5\u5230 mongo\uff0c\u4f46\u6211\u4ecd\u7136\u6536\u5230\u4ee5\u4e0b\u9519\u8bef\uff1a<\/p>\n<pre>http: panic serving 172.27.0.8:40176: runtime error: invalid memory address or nil pointer dereference<\/pre>\n<p>\u6211\u6b63\u5728\u521d\u59cb\u5316\u6570\u636e\u5e93\u8fde\u63a5\u7684 main.go \u770b\u8d77\u6765\u50cf\u8fd9\u6837<\/p>\n<pre>func main(){\n   \n      \/\/connect to mongo\n      mongoclient,err:=connecttomongo()\n      if err!=nil{\n          log.panic(err)\n      }\n      client=mongoclient\n  \n      \/\/create a context that mongo needs in order to disconnect\n      ctx,_:=context.withtimeout(context.background(), 15*time.second)\n     \/\/ ctx,cancel:=context.withtimeout(context.background(), 15*time.second)\n      \/\/defer cancel()\n      \n  \n      \/\/close connection\n      defer func ()  {\n          if err =client.disconnect(ctx); err!=nil{\n              panic(err)\n          }\n      }() \n\n    muxrouter := mux.newrouter().strictslash(true)\n\n    \/\/specify who's allowed to connect\n    c:=cors.new(cors.options{ \n        allowedorigins: []string{\"https:\/\/*\", \"http:\/\/*\"},\n        allowedmethods: []string{\"get\", \"post\", \"put\", \"delete\", \"options\"},\n        allowedheaders: []string{\"accept\", \"authorization\", \"content-type\", \"x-csrf-token\"},\n        exposedheaders: []string{\"link\"},\n        allowcredentials: true,\n        maxage: 300,\n})\n    router := addroutes(muxrouter)\n    handler := c.handler(router)\n    log.println(\"service stratring at o  port \",webport)\n\n    sterr := http.listenandserve(\":9090\", handler) \/\/uncomment this line when using docker\n    if sterr != nil {\n        log.fatal(\"error starting http server :: \", err)\n        return\n    }\n\n    log.println(\"service started at port \",webport)\n\n\n    \n  \n\n}\n\nfunc connecttomongo()(*mongo.client,error){\n    mongousername := os.getenv(\"mongousername\")\n    mongopassword := os.getenv(\"mongopassword\")\n    \/\/create connection options\n    clientoptions:=options.client().applyuri(mongourl)\n    clientoptions.setauth(options.credential{\n        username: mongousername,\n        password: mongopassword,\n    })\n\n    \/\/connect\n    c,err:=mongo.connect(context.todo(),clientoptions)\n    if err!=nil{\n        log.println(\"error connecting to mongo\",err)\n        return nil,err\n    }\n    log.println(\"connected to mongo\")\n    return c,nil\n}<\/pre>\n<p>\u5728\u4e00\u4e2a\u5355\u72ec\u7684\u6587\u4ef6 models.go \u4e2d\uff0c\u6211\u5c1d\u8bd5\u5c06\u6570\u636e\u63d2\u5165\u6570\u636e\u5e93\uff0c\u5982\u4e0b\u6240\u793a\uff1a<\/p>\n<pre>var client *mongo.Client\nfunc  Insert(entry LogEntry)error{\n    log.Printf(\"Attempting to insert %s\", entry)\n    log.Printf(\"client s  %s\", client)\n    \/\/db:=client.Database(\"logs\")\n    \/\/log.Printf(\"database  is  %s\", db)\n    \n   collection:=client.Database(\"logs\").Collection(\"logsCollection\")\n    log.Printf(\"collection is  %s\", collection)\n\n    _,err :=collection.InsertOne(context.TODO(), LogEntry{\n        Name: entry.Name,\n        Data: entry.Data,\n        CreatedAt: time.Now(),\n        UpdatedAt: time.Now(),\n    })\n    if err!=nil{\n        log.Println(\"Error inserting new record into logs collection\",err)\n        return err\n    }\n    log.Println(\"insert successful\")\n    return nil\n}<\/pre>\n<p>\u6709\u4eba\u80fd\u53d1\u73b0\u6211\u505a\u9519\u4e86\u4ec0\u4e48\u5417\uff1f<\/p>\n<p> <\/p>\n<h2>\u6b63\u786e\u7b54\u6848<\/h2>\n<p> <\/p>\n<p>\u7531\u4e8e\u9519\u8bef\u662f\u901a\u7528\u7684\uff08\u4f8b\u5982\uff0c\u672a\u63d0\u4f9b\u9519\u8bef\u7684\u884c\u53f7\uff09\uff0c\u6211\u5c06\u5206\u4eab\u4e00\u4e2a\u53ef\u884c\u7684\u89e3\u51b3\u65b9\u6848\uff0c\u4e5f\u8bb8\u53ef\u4ee5\u5e2e\u52a9\u60a8\u627e\u51fa\u95ee\u9898\u6240\u5728\u3002\u6211\u5148\u5206\u4eab\u4e00\u4e0b\u4ee3\u7801\u3002<\/p>\n<h3><code>main.go<\/code> \u6587\u4ef6<\/h3>\n<pre>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n\n    \"go.mongodb.org\/mongo-driver\/bson\"\n    \"go.mongodb.org\/mongo-driver\/mongo\"\n    \"go.mongodb.org\/mongo-driver\/mongo\/options\"\n)\n\ntype LogEntry struct {\n    Name      string\n    Data      string\n    CreatedAt time.Time\n    UpdatedAt time.Time\n}\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)\n    defer cancel()\n\n    clientOptions := options.Client().ApplyURI(\"mongodb:\/\/root:root@localhost:27017\")\n    mongoClient, err := mongo.Connect(ctx, clientOptions)\n    if err != nil {\n        panic(err)\n    }\n    defer mongoClient.Disconnect(ctx)\n\n    demoDb := mongoClient.Database(\"demodb\")\n    myCollection := demoDb.Collection(\"myCollection\")\n\n    \/\/ delete documents\n    if _, err := myCollection.DeleteMany(ctx, bson.M{}); err != nil {\n        panic(err)\n    }\n\n    \/\/ insert data\n    insertRes, err := myCollection.InsertOne(ctx, LogEntry{\n        Name:      \"lorem ipsum\",\n        Data:      \"lorem ipsum\",\n        CreatedAt: time.Now(),\n        UpdatedAt: time.Now(),\n    })\n    if err != nil {\n        panic(err)\n    }\n    fmt.Println(insertRes.InsertedID)\n\n    \/\/ query data\n    cursor, err := myCollection.Find(ctx, bson.M{})\n    if err != nil {\n        panic(err)\n    }\n    var logEntries []bson.M\n    if err = cursor.All(ctx, &amp;logEntries); err != nil {\n        panic(err)\n    }\n    for _, v := range logEntries {\n        fmt.Println(v)\n    }\n}\n<\/pre>\n<p>\u4e3a\u4e86\u6f14\u793a\uff0c\u6211\u5c06\u6240\u6709\u903b\u8f91\u653e\u5728\u4e00\u4e2a\u6587\u4ef6\u4e2d\u3002\u5728\u6b64\u6587\u4ef6\u4e2d\uff0c\u6211\u6267\u884c\u4e86\u4ee5\u4e0b\u6b65\u9aa4\uff1a<\/p>\n<ol>\n<li>\u8bbe\u7f6e mongodb \u8fde\u63a5\u3002<\/li>\n<li>\u8fde\u63a5\u5230\u6570\u636e\u5e93\u4ee5\u53ca\u8be5\u6570\u636e\u5e93\u4e2d\u7684\u96c6\u5408\u3002<\/li>\n<li>\u5220\u9664\u6240\u6709\u5df2\u6709\u7684\u6587\u6863\uff08\u53ea\u662f\u4e3a\u4e86\u66f4\u6e05\u6670\uff09\u3002<\/li>\n<li>\u5728 <code>mycollection<\/code> \u96c6\u5408\u4e2d\u63d2\u5165\u65b0\u7684 <code>logentry<\/code> \u5b9e\u4f8b\u3002<\/li>\n<li>\u68c0\u7d22 <code>mycollection<\/code> \u96c6\u5408\u4e2d\u7684\u6240\u6709\u6761\u76ee\u3002<\/li>\n<\/ol>\n<p>\u6700\u540e\u8981\u63d0\u5230\u7684\u662f\u6211\u7528\u6765\u8fd0\u884c\u5bb9\u5668\u7684 docker \u547d\u4ee4\uff1a<\/p>\n<p><code>docker\u8fd0\u884c-d -p 27017:27017 --name mymongo -e mongo_initdb_root_username=root -e mongo_initdb_root_password=root mongo:latest<\/code><\/p>\n<p>\u5982\u679c\u60a8\u575a\u6301\u4f7f\u7528\u6211\u7684\u89e3\u51b3\u65b9\u6848\uff0c\u60a8\u5e94\u8be5\u80fd\u591f\u6beb\u65e0\u95ee\u9898\u5730\u63d2\u5165\u6587\u6863\u3002\u5982\u679c\u4e0d\u662f\u8fd9\u6837\uff0c\u8bf7\u544a\u8bc9\u6211\uff0c\u6211\u4f1a\u5c3d\u529b\u5e2e\u52a9\u60a8\uff01<\/p>\n<p>\u672c\u7bc7\u5173\u4e8e\u300aGolang\u65e0\u6cd5\u5728MongoDB\u4e2d\u521b\u5efa\u6587\u6863\u300b\u7684\u4ecb\u7ecd\u5c31\u5230\u6b64\u7ed3\u675f\u5566\uff0c\u4f46\u662f\u5b66\u65e0\u6b62\u5883\uff0c\u60f3\u8981\u4e86\u89e3\u5b66\u4e60\u66f4\u591a\u5173\u4e8eGolang\u7684\u76f8\u5173\u77e5\u8bc6\uff0c\u8bf7\u5173\u6ce8\u7c73\u4e91\u516c\u4f17\u53f7\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5f53\u524d\u4f4d\u7f6e\uff1a &gt; &gt; &gt; &gt; Golang\u65e0\u6cd5\u5728MongoDB\u4e2d\u521b\u5efa\u6587\u6863 Golang\u65e0\u6cd5\u5728MongoDB\u4e2d\u521b\u5efa\u6587\u6863 \u6765\u6e90\uff1astackoverflow 2024-04-19 23:36:32 0\u6d4f\u89c8 \u6536\u85cf \u672c\u7bc7\u6587\u7ae0\u7ed9\u5927\u5bb6\u5206\u4eab\u300aGolang\u65e0\u6cd5\u5728MongoDB\u4e2d\u521b\u5efa\u6587\u6863\u300b\uff0c\u8986\u76d6\u4e86Golang\u7684\u5e38\u89c1\u57fa\u7840\u77e5\u8bc6\uff0c\u5176\u5b9e\u4e00\u4e2a\u8bed\u8a00\u7684\u5168\u90e8\u77e5\u8bc6\u70b9\u4e00\u7bc7\u6587\u7ae0\u662f\u4e0d\u53ef\u80fd\u8bf4\u5b8c\u7684\uff0c\u4f46\u5e0c\u671b\u901a\u8fc7\u8fd9\u4e9b\u95ee\u9898\uff0c\u8ba9\u8bfb\u8005\u5bf9\u81ea\u5df1\u7684\u638c\u63e1\u7a0b\u5ea6\u6709\u4e00\u5b9a\u7684\u8ba4\u8bc6(B \u6570)\uff0c\u4ece\u800c\u5f25\u8865\u81ea\u5df1\u7684\u4e0d\u8db3\uff0c\u66f4\u597d\u7684\u638c\u63e1\u5b83\u3002 \u95ee\u9898\u5185\u5bb9 \u6211\u6b63\u5728\u5c1d\u8bd5\u5c06\u6587\u6863\u63d2\u5165 mongodb\uff0c\u4f46\u5c3d\u7ba1\u6210\u529f\u8fde\u63a5\u5230 mongo\uff0c\u4f46\u6211\u4ecd\u7136\u6536\u5230\u4ee5\u4e0b\u9519\u8bef\uff1a http: panic serving 172.27.0.8:40176: runtime error: invalid memory address or nil pointer dereference \u6211\u6b63\u5728\u521d\u59cb\u5316\u6570\u636e\u5e93\u8fde\u63a5\u7684 main.go \u770b\u8d77\u6765\u50cf\u8fd9\u6837 func main(){ \/\/connect to mongo mongoclient,err:=connecttomongo() if err!=nil{ log.panic(err) } client=mongoclient \/\/create a context that mongo needs in order to disconnect [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[17],"tags":[],"class_list":["post-41384","post","type-post","status-publish","format-standard","hentry","category-docker"],"_links":{"self":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/41384","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/comments?post=41384"}],"version-history":[{"count":0,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/41384\/revisions"}],"wp:attachment":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/media?parent=41384"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/categories?post=41384"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/tags?post=41384"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}