> Install the required module named mongoose using the following command:
npm install mongoose
> Setup connection in server.js and refer source code from link here. Let create folder named models and define a new model named Message as below:
const mongoose = require("mongoose");
const MessageSchema = new mongoose.Schema({
conversation_id: {
type: String,
unique: false,
required: true,
},
owner_message_id: {
type: String,
unique: false,
required: true,
},
message: {
type: String,
unique: false,
required: true,
},
date_created: {
type: Date,
required: true
}
});
const Message = mongoose.model("Message", MessageSchema);
module.exports = Message;
> If we understand MVC, Message is exactly Model and need Controller. Here is MessageController.js as below:
const Message = require("../models/Message");
const Logger = require("../utils/logger");
const initModelMessage = async (req, res) => {
try {
await Message.createCollection().then(function (collection) {
Logger.info('Collection Message is created!');
});
} catch (err) {
Logger.error(err);
return res.json({
success: false,
message: "Error with creating Message Collection!.",
});
}
}
module.exports = {
initModelMessage
};
> For the logger.js, you can refer winston for Node.js Application. We have router.js as below:
const { initModelMessage } = require("../controllers/MessageController"),
express = require("express"),
router = express.Router();
router.post("/init", initModelMessage);
module.exports = router;
> Use express.js to wrap routes and define RESTful APIs for MessageController.js.
const path = require('path'),
express = require('express'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
routers = require("../routes/router"),
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());
app.use("/api/message", routers);
return app;
}
> Here is logger.js when apply Winston dependency to debug Node.js application.
const { createLogger, format, transports } = require('winston');
module.exports = createLogger({
transports:
new transports.File({
filename: 'logs/server.log',
format:format.combine(
format.timestamp({format: 'MMM-DD-YYYY HH:mm:ss'}),
format.align(),
format.printf(info => `${info.level}: ${[info.timestamp]}: ${info.message}`),
)}),
});
> Finally, we will move to server.js where located in root folder of Node.js application.
const express = require("./config/express.js"),
mongoose = require("mongoose");
const Logger = require('./utils/logger');
const app = express.init();
const server = require("http").createServer(app);
server.listen(3000, () => {
Logger.info('Server started on port 3000');
});
app.get("/", (req, res) => {
res.send("<h1>Your server has start from deployment!!</h1>");
});
app.disable('etag'); // Fix error 403 in Node.js application
/** 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
});
> Here is folder structure as below:
+ nodejs
+ nodejs/config/express.js
+ nodejs/utils/logger.js
+ nodejs/routes/router.js
+ nodejs/controllers/MessageController.js
+ nodejs/models/Message.js
+ nodejs/server.js
> We can create mongoose.js file in folder config as below:
const mongoose = require("mongoose");
/** 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
});
module.exports = mongoose;
> Use module.exports to export instance for mongoose. To use this, you can import as below:
const mongoose = require('./config/mongoose');
> How to delete all collections in Mongoose? Here is what we can do? Assumption that implementation was in MessageControler.js.
...
async function clearCollections() {
const collections = mongoose.connection.collections;
await Promise.all(Object.values(collections).map(async (collection) => {
await collection.deleteMany({});
}));
}
...
> How to find item in mongo collection? There two ways as below:
async function getMessage(UIID) {
return Message.findOne({message_id: UIID}).exec();
}
async function getMessagePromise(UIID) {
return new Promise((resolve) => {
Message.findOne({message_id: UIID}, function (err, Message) {
resolve(Message);
});
});
}
const init = async (req, res) => {
const promiseConversation = getConversation(UIID);
promiseMessage.then(message => {
Logger.info(message);
Logger.info(message.message_id);
});
let promiseConn = await getConversationPromise(UIID);
Logger.info(promiseConn);
Logger.info(promiseConn.message_id);
};
> How to edit item in MongoDB collection?
const editMessage = async (req, res) => {
let promiseEdit = await new Promise((resolve) => {
Message.updateOne({'conversation_id': req.body.conversation_id}, {$set : {"message": req.body.message}}, function (err, data) {
if (err != null) resolve(err);
else resolve(data);
});
});
if (promiseEdit.modifiedCount > 0) {
return res.json({
success: true,
message: 'Update successfully!'
});
} else {
return res.json({
success: false,
message: 'Update failed!'
});
}
}
Note: You can read more about updateMany() method. Here is the following syntax:
<Collection Name>.updateMany(filter, update, options);
> What about delete item in collection? Here what we have as below:
const deleteMessage = async (req, res) => {
let deletePromise = await new Promise((resolve) => {
Message.deleteOne({ conversation_id: req.body.conversation_id }, function (err, data) {
if (err != null) resolve(err);
else resolve(data);
});
});
if (deletePromise.deletedCount > 0) {
return res.json({
success: true,
message: 'Delete successfully!'
});
} else {
return res.json({
success: false,
message: 'Delete failed!'
});
}
}
Note: You can reference deleteMany in mongoose.