avatar
Connect Node.js App to MongoDB Javascript

> Get source code from link here. You can npm start to run Nodejs server at port 3000.

npm start

> [email protected] start C:\Users\admin\Documents\nodejs
> node server.js

Server started on port 3000

> As you can see here, we will need some configurations in advance upon comes along with express. Hence, you will create folder named config and add express.js inside the folder.

const path = require('path'),
    express = require('express'),
    morgan = require('morgan'),
    bodyParser = require('body-parser'),
    cors = require('cors');

module.exports.init = () => {
    const app = express();
    app.use(cors());
    app.use(morgan('dev'));
    app.use(bodyParser.urlencoded({ extended: true}));
    app.use(bodyParser.json());
    return app;
} 

Note: Our server.js should update again after rewriting express.js file.

const express = require("./config/express.js");

const app = express.init();
const server = require("http").createServer(app);

server.listen(3000, () => {
    console.log('Server started on port 3000');
});

> The next step, we will create controllers and routes folder. Make Controller to control REST APIs from client whenever they make an request.

+ nodejs/routes/router.js
+ nodejs/controllers/MessageController.js
+ nodejs/models/Message.js
+ nodejs/server.js

> router.js - declare get/post/put/delete route for REST APIs. Your custom Controller has methods which are equivalent to your get/post/put/delete router.

const { addMessage, getMessages } = require("../controllers/MessageController"),
  express = require("express"),
  router = express.Router();

router.post("/addMessage", addMessage);
router.get("/getMessages", getMessages);

module.exports = router;

> MessageController.js - Follow up model MV-REST (Model - Controller - REST APIs). We will need models to handle for query/update/delete data from any database (such as Postgresql or Mongodb Atlas).

const Message = require("../models/Message");
const addMessage = async (req, res) => {
    try {
        const message = await Message.create({
            message: req.body.message,
            date_created: req.body.date_created
        });
        return res.json({
            success: true,
            message: "Message added successfully!",
        });
    } catch (error) {
        return res.json({
            success: false,
            message: "Error with adding message. See server console for more info.",
        });
    }
};
const getMessages = async (req, res) => {
    try {
        const messages = await new Promise((resolve) => { 
            Message.find({}, function(err, data) { 
                if (err !== null) {
                    resolve(err);
                } else {
                    resolve(data);
                }
            });
        }); 
        return res.json({
            success: true,
            message: messages
        });
    } catch (error) {
        return res.json({
            success: false,
            message: error
        });
    }
};
module.exports = {
    addMessage,
    getMessages,
};

> Go to express.js to update routes configured from file router.js.

routers = require("../routes/router"),
...
app.use("/api/message", routers);

> We will need to configure Node.js to connect Mongo Database Atlas. Here what we go for the next step. Reference link here to get how to configure mongodb by mongoose library.

const express = require("./config/express.js"),
    mongoose = require("mongoose");

const app = express.init();
const server = require("http").createServer(app);
server.listen(3000, () => {
    console.log('Server started on port 3000');
});

/** Connect MongoDB from Node.js application */
mongoose.set('strictQuery', false);
mongoose.connect('mongodb+srv://flagtick:[email protected]/chatbox?retryWrites=true&w=majority', {
    useNewUrlParser: true, 
    useUnifiedTopology: true 
});

const connection = mongoose.connection;
connection.once("open", () => {
    const messageCollectionStream = connection.collection("messages").watch();
    messageCollectionStream.on("change", (change) => {
        switch (change.operationType) {
          case "insert":
            break;
          case "delete":
            break;
        }
    });
});

Note: The function watch() will help to detect any change for this collection. So we may use this feature for chatbox or any purpose.

> There are two endpoints was created here. You can use postman to test for both.

http://localhost:3000/api/message/getMessages

http://localhost:3000/api/message/addMessage

> Go to MongoDatabase Atlas and check collection named messages in table named chatbox. You can also get source code from link here.

You need to login to do this manipulation!