Hi guys, this is my first post and I want to share a simple Node.js REST API (Express) that includes Docker, Redis and MongoDB.
You can run this project with docker-compose, we won't explain anything about it but you refer these links Docker and Docker Compose. Check the repo link at the end to be able to run the GitHub project.
In the file api.js, we use mongoose to connect to MongoDB server:
mongoose.connect(`mongodb://${process.env.MONGO_INITDB_ROOT_USERNAME}:${process.env.MONGO_INITDB_ROOT_PASSWORD}@${process.env.MONGO_CONTAINER_NAME}/${process.env.MONGO_INITDB_DATABASE}?authMechanism=SCRAM-SHA-1&authSource=admin`,
{ useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true }
, (err) => {
if (err) {
console.log('could\'t connect to Mongo DB ', err);
}
});
Inside libs/redis-client.js you can see the Redis connection:
const redis = require('redis');
const { promisify } = require('util');
const client = redis.createClient(process.env.REDIS_URL);
client.on("error", (error) => {
console.error(`Error to connect Redis: ${error}`);
});
Then let's use it:
mongoose -> api/routes/users.js. (Check User schema inside models/user)
// retrieve users
let users = await User.find({}).lean().exec();
redis -> api/routes/users.js.
// retrieve user
const rawData = await redisClient.getAsync(req.params.email);
// save user
await redisClient.setAsync(req.params.email, JSON.stringify(user));
The repo is available at: https://github.com/renacargnelutti/express-mongo-redis
I hope you enjoy the post!
Let me know any question.
Top comments (2)
Where is Docker integration!
Hi dude! Sorry for being late.
This post is only a summary, you can check it out the complete code on GitHub. There check the 'docker' folder and the README.md.