[英]MongoDB and NodeJS cannot create collection
So I used this exact code about 8 months ago and it worked fine, now suddenly this way of setup does not seem to work.所以我在大约 8 个月前使用了这个确切的代码,它工作得很好,现在突然这种设置方式似乎不起作用。 I cannot manage to find what is wrong here and it seems the database just is not connecting at all.我无法在这里找到问题所在,而且似乎数据库根本没有连接。 Is there a better way to go about this?有没有更好的方法来解决这个问题?
'use strict' const express = require('express'); const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://toor:root@mongodbdatabase:27017/' const app = express(); const PORT = 8080; const HOST = '0.0.0.0'; let con; MongoClient.connect(url, (err, db) => { con = db.db("mongodbdatabase"); }) app.use('/', express.static('public')); app.get('/createDatabase', (req, res) => { con.createCollection("HiveDB", function(err, result) { if (err) throw err; console.log("Collection Created") }) res.send(); }) console.log(`Listening on port ${PORT}`) app.listen(PORT, HOST);
Here is the error that I am getting when navigating to localhost:83/createDatabase这是我在导航到 localhost:83/createDatabase 时遇到的错误
TypeError: Cannot read properties of undefined (reading 'createCollection')
at /usr/src/app/server.js:28:9
at Layer.handle [as handle_request] (/usr/src/app/node_modules/express/lib/router/layer.js:95:5)
at next (/usr/src/app/node_modules/express/lib/router/route.js:144:13)
at Route.dispatch (/usr/src/app/node_modules/express/lib/router/route.js:114:3)
at Layer.handle [as handle_request] (/usr/src/app/node_modules/express/lib/router/layer.js:95:5)
at /usr/src/app/node_modules/express/lib/router/index.js:284:15
at Function.process_params (/usr/src/app/node_modules/express/lib/router/index.js:346:12)
at next (/usr/src/app/node_modules/express/lib/router/index.js:280:10)
at SendStream.error (/usr/src/app/node_modules/serve-static/index.js:121:7)
at SendStream.emit (node:events:537:28)
Im running with docker compose as well我也在使用 docker compose 运行
Dockerfile: Dockerfile:
FROM node:latest
EXPOSE 8080
WORKDIR /usr/src/app
RUN npm install express --save
RUN npm install mongodb --save
RUN npm install -g loadtest --save
COPY server.js /usr/src/app/server.js
COPY /public /usr/src/app/public
CMD ["node", "server.js"]
docker-compose.yml:码头工人-compose.yml:
version: '3'
services:
mainserver:
build: ./main
depends_on:
- mongodbdatabase
container_name: mainServer
ports:
- "83:8080"
mongodbdatabase:
image: mongo
container_name: monDataBase
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: toor
MONGO_INITDB_ROOT_PASSWORD: root
I will direct you to the relevant documentation from the mongodb client github readme here我将引导您从 mongodb 客户端 github 自述文件中查看相关文档
In the code snippet you have pasted, you set the con
variable with the MongoClient
connection but what if the connection fails (and err
is provided) ?在您粘贴的代码片段中,您使用MongoClient
连接设置con
变量,但是如果连接失败(并且提供了err
)怎么办? So the assignment to con
probably failed and thats the reason it is undefined
in the context of the router.所以分配给con
可能失败了,这就是它在路由器上下文中undefined
的原因。
I would recommend to copy & paste the example from the link i provided.我建议从我提供的链接中复制并粘贴示例。
Using the async/await syntax you can provide the mongodb client to the route handler.使用 async/await 语法,您可以将 mongodb 客户端提供给路由处理程序。
And here is a code snippet using your example:这是使用您的示例的代码片段:
'use strict'
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://toor:root@mongodbdatabase:27017/'
const app = express();
const PORT = 8080;
const HOST = '0.0.0.0';
async function init() {
try{
const client = await new MongoClient(url).connect()
}catch(err) {
console.error(err.message)
}
const db = client.db("HiveDB")
app.use('/', express.static('public'));
app.get('/createDatabase', (req, res) => {
db.createCollection("HiveDB", function(err, result) {
if (err) throw err;
console.log("Collection Created")
})
res.send();
})
app.listen(PORT, HOST,()=>{
console.log(`Listening on port ${PORT}`)
});
}
init()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.