MongoDB容器连接

huangapple go评论91阅读模式
英文:

MongoDB Container Connection

问题

这是我第一次尝试MongoDB。我只是尝试简单地成功连接到它。我正在按照W3教程进行操作,链接在这里:https://www.w3schools.com/nodejs/nodejs_mongodb.asp

docker-compose.yml

version: '3.1'
services:
  mongo:
    image: mongo
    restart: unless-stopped
    ports:
      - 27017:27017
    volumes:
      - /home/username/mongodb/data:/data/db
  mongo-express:
    image: mongo-express
    restart: unless-stopped
    ports:
      - 8089:8081

通过这个配置,mongo-express的用户界面似乎正常工作。我可以创建一个数据库等...

但是,以下部分不起作用:

create_db_test.js

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mytestdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});

........

node create_db_test.js

然后它就一直卡住了。在命令行上只有一个空白行,什么都不会发生。数据库没有被创建。容器的日志输出如下:

mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:04:20.449+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.18.0.1:39946","uuid":"abbbc8ad-fceb-4a6b-b6e4-12d123a837b7","connectionId":2,"connectionCount":2}}
mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:04:20.469+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn2","msg":"client metadata","attr":{"remote":"172.18.0.1:39946","client":"conn2","doc":{"driver":{"name":"nodejs","version":"5.5.0"},"platform":"Node.js v18.12.1, LE","os":{"name":"linux","architecture":"arm64","version":"6.1.25-37.47.amzn2023.aarch64","type":"Linux"}}}}
mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:04:30.983+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.18.0.1:60246","uuid":"47895fe4-78f3-4401-a886-4d5ef832c66b","connectionId":3,"connectionCount":3}}
mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:04:30.985+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn3","msg":"client metadata","attr":{"remote":"172.18.0.1:60246","client":"conn3","doc":{"driver":{"name":"nodejs","version":"5.5.0"},"platform":"Node.js v18.12.1, LE","os":{"name":"linux","architecture":"arm64","version":"6.1.25-37.47.amzn2023.aarch64","type":"Linux"}}}}

当我用Ctrl-C中断create_db_test.js时,容器日志建议连接一直开着,现在已经结束了:

mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:05:10.053+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn3","msg":"Connection ended","attr":{"remote":"172.18.0.1:60246","uuid":"47895fe4-78f3-4401-a886-4d5ef832c66b","connectionId":3,"connectionCount":2}}
mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:05:10.053+00:00"},"s":"I",  "c":"-","id":20883,   "ctx":"conn2","msg":"Interrupted operation as its client disconnected","attr":{"opId":620}}
mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:05:10.054+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn2","msg":"Connection ended","attr":{"remote":"172.18.0.1:39946","uuid":"abbbc8ad-fceb-4a6b-b6e4-12d123a837b7","connectionId":2,"connectionCount":1}}

我也尝试了这个(其中"mydb"已经通过mongo-express创建)但结果相同:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydb");
    var myobj = { name: "Company Inc", address: "Highway 37" };
    dbo.collection("customers").insertOne(myobj, function(err, res) {
      if (err) throw err;
      console.log("1 document inserted");
      db.close();
    });
});

我在这里漏掉了什么?

英文:

This is my first time trying MongoDB. I'm just trying to simply connect to it successfully. I'm following the W3 tutorial here: https://www.w3schools.com/nodejs/nodejs_mongodb.asp

docker-compose.yml

version: '3.1'
services:
  mongo:
    image: mongo
    restart: unless-stopped
    ports:
      - 27017:27017
    volumes:
      - /home/username/mongodb/data:/data/db
  mongo-express:
    image: mongo-express
    restart: unless-stopped
    ports:
      - 8089:8081

With that, the mongo-express UI seems to work fine. I can create a database etc...

but, this does not work:

create_db_test.js

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mytestdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});

........

node create_db_test.js

and this just hangs. There's just a blank line on the command line and it does nothing. The database is not created. The log output from the container looks like this:

mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:04:20.449+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.18.0.1:39946","uuid":"abbbc8ad-fceb-4a6b-b6e4-12d123a837b7","connectionId":2,"connectionCount":2}}
mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:04:20.469+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn2","msg":"client metadata","attr":{"remote":"172.18.0.1:39946","client":"conn2","doc":{"driver":{"name":"nodejs","version":"5.5.0"},"platform":"Node.js v18.12.1, LE","os":{"name":"linux","architecture":"arm64","version":"6.1.25-37.47.amzn2023.aarch64","type":"Linux"}}}}
mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:04:30.983+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.18.0.1:60246","uuid":"47895fe4-78f3-4401-a886-4d5ef832c66b","connectionId":3,"connectionCount":3}}
mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:04:30.985+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn3","msg":"client metadata","attr":{"remote":"172.18.0.1:60246","client":"conn3","doc":{"driver":{"name":"nodejs","version":"5.5.0"},"platform":"Node.js v18.12.1, LE","os":{"name":"linux","architecture":"arm64","version":"6.1.25-37.47.amzn2023.aarch64","type":"Linux"}}}}

When I interrupt create_db_test.js with Ctrl-C, the container log suggests that the connection has been open the whole time and is now ended:

mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:05:10.053+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn3","msg":"Connection ended","attr":{"remote":"172.18.0.1:60246","uuid":"47895fe4-78f3-4401-a886-4d5ef832c66b","connectionId":3,"connectionCount":2}}
mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:05:10.053+00:00"},"s":"I",  "c":"-",        "id":20883,   "ctx":"conn2","msg":"Interrupted operation as its client disconnected","attr":{"opId":620}}
mongodb-mongo-1          | {"t":{"$date":"2023-05-27T16:05:10.054+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn2","msg":"Connection ended","attr":{"remote":"172.18.0.1:39946","uuid":"abbbc8ad-fceb-4a6b-b6e4-12d123a837b7","connectionId":2,"connectionCount":1}}

I've also tried this (where "mydb" is already created through mongo-express) with the same result:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydb");
    var myobj = { name: "Company Inc", address: "Highway 37" };
    dbo.collection("customers").insertOne(myobj, function(err, res) {
      if (err) throw err;
      console.log("1 document inserted");
      db.close();
    });
});

What am I missing here?

答案1

得分: 1

根据 @rickhg12hs 的建议,已删除对回调函数的支持。以下代码有效:

const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017/";

const client = new MongoClient(uri);

async function run() {
  try {
    console.log("Trying insert....");
    const database = client.db('mydb');
    const customers = database.collection('customers');
    const myobj = { name: "Company Inc", address: "Highway 37" };
    const result = await customers.insertOne(myobj);
    console.log(result);
  } finally {
    // 确保在完成/出错时关闭客户端
    await client.close();
    console.log("Done.");
  }
}
run().catch(console.dir);

请注意,我已将代码部分保持不变,只翻译了注释和控制台输出。

英文:

Per @rickhg12hs suggestion, support for callbacks has been removed. The following code works:

const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017/";

const client = new MongoClient(uri);

async function run() {
  try {
    console.log("Trying insert....");
    const database = client.db('mydb');
    const customers = database.collection('customers');
    const myobj = { name: "Company Inc", address: "Highway 37" };
    const result = await customers.insertOne(myobj);
    console.log(result);
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
    console.log("Done.");
  }
}
run().catch(console.dir);

huangapple
  • 本文由 发表于 2023年5月28日 03:19:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76348642.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定