Я запускаю пример кода, где я анализирую свои переменные env для mongoDB из докера, запускаемого в мой узел js.
Это мой текущий файл конфигурации БД
const mongoClient = require('mongodb').MongoClient;
const mongoDbUrl = process.env.MONGODB_URL;
console.log(process.env.MONGODB_URL)
let mongodb;
function connect(callback){
mongoClient.connect(mongoDbUrl, (err, db) => {
mongodb = db;
callback();
});
}
function get(){
return mongodb;
}
function close(){
mongodb.close();
}
module.exports = {
connect,
get,
close
};
Это мой файл Docker
FROM node:latest
ENV MONGODB_URL=${MONGODB_URL}
WORKDIR /app
COPY package.json /app
COPY . /app
RUN npm install
EXPOSE 4000
CMD ["node", "server.js"]
В моем server.js я тестировал, где можно подключиться к URL-адресу mongoDB, проанализированному в
var bodyParser = require('body-parser')
, MongoClient = require('mongodb').MongoClient
, PORT = 4000
, instantMongoCrud = require('express-mongo-crud') // require the module
, express = require('express')
, app = express()
, path = require('path')
, options = { //specify options
host: `localhost:${PORT}`
}
, db = require('./connection')
// connection to database
db.connect(() => {
app.use(bodyParser.json()); // add body parser
app.use(bodyParser.urlencoded({ extended: true }));
// get function
app.get('/', function(req, res) {
db.get().collection('users').find({}).toArray(function(err, data){
if (err)
console.log(err)
else
res.render('../views/pages/index.ejs',{data:data});
});
});
// post functions
app.post('/adduser', function(req, res) {
var name=req.body.name
var email=req.body.email
var occupation=req.body.occupation
var username=req.body.username
console.log(name)
console.log(email)
db.get().collection('users').count({email : email}, function(err, result){
console.log(result)
if (result){
console.log("user exists")
res.send("user exists")
}else{
db.get().collection('users').save({name:name, email:email, occupation:occupation, username:username}, {w:1},function (err, result) {
if (err){
console.log("error")
} else{
console.log("success")
res.send("successful")
}
});
}
});
});
// delete user
app.post('/deleteUser', function(req, res) {
var email=req.body.email
console.log(email)
db.get().collection('users').deleteOne({email: email}, function(err,result){
if (err){
console.log("error")
}else{
console.log("successfully deleted user")
res.send ("successfully deleted user")
}
});
});
app.listen(PORT, ()=>{
console.log('started');
console.log(db)
})
app.use(instantMongoCrud(options)); // use for the instant Mongo CRUD
});
Я побежал
docker run -e MONGODB_URL='mongodb://localhost:27017/user' <containerID>
и столкнулся с неопределенной проблемой подключения.
TypeError: Cannot read property 'collection' of null
at /app/app.js:24:17
Есть ли какой-нибудь совет, потому что я думал, что process.env сможет получить значение env
Спасибо.