Invoice Application Backend Using ApsaraDB for MongoDB

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: In part three of this three-part tutorial, we will explore how to create the backend of a fully functional invoice application using ApsaraDB for MongoDB.

By Sai Sarath Chandra, Alibaba Cloud Tech Share Author and Alibaba Cloud MVP

In our previous tutorial, we have created the UI for our Invoice Application. However, as discussed in our first article, desktop applications face the risk of losing valuable data.

Therefore, we will be using Alibaba Cloud’s ApsaraDB for MongoDB to save our data onto the cloud. By storing your data on the cloud, you can use this data across applications like Android, iOS, and web applications, as well as obtain the data at any time. Alibaba Cloud ensures that the data is readily available every time. You can also leverage the Automatic Elastic Scaling provided by Alibaba Cloud to suit your business at any time.

Setting Up the Application Backend

Now we will discuss on the backend we are creating for the invoicing Application.

The API we are creating are based on Node server & ExpressJS framework.

Clone the code at https://github.com/saichandu415/Electron-Invoice-ApsaraDB-MongoDB and Naviagate to “Invoice_Backend” folder. Open the file using your favorite text editor.

There are only 2 files for our interest:

  • Package.json
    This file holds all the information regarding the dependencies, such as development dependencies.
  • Server.js
    This is the key file where we write the logic. In production scenarios it is recommended to use the frameworks like Loopback to have a high-performance API with much more control.

In Package.json, we have a standard set of dependencies:

  • Sprint-JS, mongoDB, node-UUID, formidable – for connecting to the database and creating the URL’s at runtime
  • Express and body-parser – are used to create the API’s and get the incoming request in a JSON format.

In Server.js, we have the following code

 http.createServer(app).listen(443, function () {
  console.log('Server for Invoice Backend running on port 443!');
});

The above Is the standard set of way to create a http server listening at 443 for requests. Make sure you have the below imports before starting off.

const bodyParser = require("body-parser");
const express = require("express");
const app = express();
var uuid = require('node-uuid');
var http = require('http');
var fs = require('fs');
var sprintf = require("sprintf-js").sprintf;
var mongoClient = require('mongodb').MongoClient;

All these imports are needed for the application to perform normally.

app.use(bodyParser.json());

This line above will unparses the body information which we send into json format before it goes through the Database else it results in an error.

Here I am using console in that way you can see the information as soon as the application passes the console.log() line and understands what’s happening here. In production it is not advisable to have console statements. Instead you will have a proper logging format to achieve the same.

// ApsaraDB for MongoDB related configurations
var host1 = "dds-6gj540e0c157941.mongodb.ap-south-7.rds.aliyuncs.com";
var port1 = 3012;
var host2 = "dds-6gj54080c157942.mongodb.ap-south-7.rds.aliyuncs.com";
var port2 = 3012;
var username = "root";
var password = "Mongodb@12345";
var replSetName = "mgset-1050000641";
var demoDb = "admin";

Your MongoDB related information needs to go through here to connect and perform operations on your database.

app.post('/data/invoice', (req, res) => {
  console.log(req.body);   
  var saveData = saveInvoiceData(req.body); 
  saveData.then(function(dbResponse){
    console.log(dbResponse);
    res.status(201).send(dbResponse);

  },function(err){
    console.log(err);
    res.status(400).send(err);
  });
});

This is the post operation which happens when they click the submit button on the application. Internally, it calls the saveInvoiceData.

The saveInvoiceData method will connect to DB, authenticate, and finds collection and pushes data into the DB.

function saveInvoiceData(collectionData) {

  console.log(collectionData);
  return new Promise(function (resolve, reject) {
    // Logic to fetch from the MongoDB
    mongoClient.connect(url, function (err, db) {
      //if error console error
      console.log(err);
      if (err) {
        // Database not connected : error thrown
        console.error("connect err:", err);
        reject(err);
      } else {
        //Database connected successfully, get the DB Object
        var adminDb = db.admin();
        //Authenticate Database
        adminDb.authenticate(username, password, function (err, result) {
          if (err) {
            console.log("authenticate err:", JSON.stringyfy(err));
            reject(err);
          } else {
            console.log('Authenticated : ', JSON.stringify(result));
            // Get the Collection handle.
            var collection = db.collection("saleData");
            collection.insertOne(collectionData,function(err,result){
              if(err){
                reject(err);
              }else{
                resolve(result);
              }
            });
          }
        });
      }
    });
  });
}

The method receives a collectionData json object. And the other information is obvious from the method comments. Notice here that the data is pushed into the collection “saleData”

The below is the GET method for getting the data related for the dashboards

app.get('/data/dashboard', (req, res) => {
  var getData = getDashboardData();
  getData.then(function(result){
    res.status(200).send(result);
  },function(err){
    console.log(err);
    res.status(400).send(err);
  });
});

The GET method calls the “getDashboardData()” to fetch the data & process it and creates a response.

function getDashboardData() {

  return new Promise(function (resolve, reject) {
    // Logic to fetch from the MongoDB
    mongoClient.connect(url, function (err, db) {
      //if error console error
      console.log(err);
      if (err) {
        // Database not connected : error thrown
        console.error("connect err:", err);
        reject(err);
      } else {
        //Database connected successfully, get the DB Object
        var adminDb = db.admin();
        //Authenticate Database
        adminDb.authenticate(username, password, function (err, result) {
          if (err) {
            console.log("authenticate err:", JSON.stringyfy(err));
            reject(err);
          } else {
            console.log('Authenticated : ', JSON.stringify(result));
            // Get the Collection handle.
            var collection = db.collection("saleData");
            collection.find({}).toArray(function (err, items) {
              if (err) {
                console.error('Unable to find data' + JSON.stringify(err));
              } else {
                console.info('data Fetched from MongoDB');
                var response = {}; 

                var datesArr = [];
                var salesArr = [];
                var ordersArr = [];

                var i =0;
                for(i=0; i<5; i++){
                  var totalSales = 0;
                var totalOrders = 0;
                  var d = new Date();
                  d.setDate(d.getDate() - i);
                  var month = d.getMonth() + 1;
                  var day = d.getDate();
                  var output = d.getFullYear() + '/' + (month < 10 ? '0' : '') + month + '/' + (day < 10 ? '0' : '') + day;
                  datesArr.push(output);
                console.log("In Loop 1 : "+i);
                  for(var k=0; k<items.length; k++){
                    var item = items[k];
                    if(item.invoiceDate == output){
                      totalSales = totalSales + item.totalAmount;
                      totalOrders = totalOrders+1;
                    }
                  }
                  salesArr.push(totalSales);
                  ordersArr.push(totalOrders);
                }
                response.datesArr = datesArr;
                response.salesArr = salesArr;
                response.ordersArr = ordersArr;
                resolve(response);
              }
            });
          }
        });
      }
    });
  });
}

There is a lot going in here. If you hit the below mentioned URI, you will see the following information.

Request : GET
http:// VM IP : PORT>/data/dashboard

Response :

{
    "datesArr": [
        "2018/03/25",
        "2018/03/24",
        "2018/03/23",
        "2018/03/22",
        "2018/03/21"
    ],
    "salesArr": [
        0,
        4197.3,
        34,
        0,
        0
    ],
    "ordersArr": [
        0,
        1,
        1,
        0,
        0
    ]
}

In the getInvoiceData(), once the database is connected, data is authenticated and fetched from collection. The method will run a loop to check the number of orders and total sale value for the last 5 days from the current data, and pushes the data into corresponding arrays.

The above mentioned response is sent to the /GET method so it will run a for loop on the entire data and constructs the response into corresponding arrays, Since this will be a CPU intensive task we have externalized it to the middleware deployed on an Alibaba Cloud ECS instance.

Previously, you need to integrate your application into the endpoint to make sure the data you receive will be in a proper format. I have used postman, which is a simple client for that purpose.

POSTMAN

The below is the screenshot of postman window

1

  • You can call have different methods like GET, POST, PUT, PATCH, DELETE
  • There is a URI/address bar which also accepts the query parameters.
  • Click the send button to make the request and get the response.
  • You can explore more about this, you can run test cases or peak performance testing. This is a free tool you can use it for commercial purposes.

Deploying the API

You should already have an Alibaba Cloud ECS set up. You can check out other tutorials on creating an ECS instance if you aren't sure about it.

Creating MongoDB instance:
1.You need to activate the ApsaraDB for MongoDB in your Alibaba Cloud console.
2.Navigate to the ApsaraDB for MongoDB console and choose the appropriate zone.
3.Click on Create Instance.
4.Carefully select all the infrastructure related configurations like RAM and Bandwidth.
5.If you are using a password, keep it carefully for future use/ reference. We will be using in our code for authentication.
6.Preview and create the instance by accepting the terms and conditions.
7.Once your instance is created, navigate to the details of the instance and Whitelist your ECS instance IP.
8.Once you navigate to whitelisting rules you will see Import ECS IP button. Upon clicking on the button, the ECS Intranet IP will be imported automatically.
9.In a few seconds, you should be able to see the “Connection String” appearing on the console. You can use this information to connect GUI MongoDB Clients to the ApsaraDB for MongoDB.
10.The other individual information is needed to connect the MongoDB through the code. Make sure you replace this information in the code to connect to your database.

Running the Code

After you copy the code to the ECS instance, you have to run the following commands for successful execution:

1.Npm install
a.This package downloads and installs all the required packages from the npm repository
2.Npm start / node app.js
a.This will run the application and once the server is started, you should be able to invoke the API.

Conclusion

During this articles we have seen what is Electron JS? We have also created the user interface along with Backend API. We also saw how we can leverage the ApsaraDB for MongoDB for desktop applications which provide value addition to the product we are creating for our customers.

The whole code is provided in the github repository. If you have question about something please raise the same as an issue at the following link:

https://github.com/saichandu415/Electron-Invoice-ApsaraDB-MongoDB

If think you can improve the code, please raise it as a pull request.

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
JSON 弹性计算 NoSQL
AMP for E-Commerce Part 3: Integrating the Entire Application with Alibaba Cloud ApsaraDB for MongoDB
In this three-part tutorial, we will explore how to create a fully functional e-commerce mobile application using AMP.
1853 0
AMP for E-Commerce Part 3: Integrating the Entire Application with Alibaba Cloud ApsaraDB for MongoDB
|
18天前
|
NoSQL MongoDB 数据库
数据库数据恢复——MongoDB数据库服务无法启动的数据恢复案例
MongoDB数据库数据恢复环境: 一台Windows Server操作系统虚拟机上部署MongoDB数据库。 MongoDB数据库故障: 管理员在未关闭MongoDB服务的情况下拷贝数据库文件。将MongoDB数据库文件拷贝到其他分区后,对MongoDB数据库所在原分区进行了格式化操作。格式化完成后将数据库文件拷回原分区,并重新启动MongoDB服务。发现服务无法启动并报错。
|
6月前
|
存储 关系型数据库 MySQL
一个项目用5款数据库?MySQL、PostgreSQL、ClickHouse、MongoDB区别,适用场景
一个项目用5款数据库?MySQL、PostgreSQL、ClickHouse、MongoDB——特点、性能、扩展性、安全性、适用场景比较
|
1月前
|
存储 NoSQL MongoDB
微服务——MongoDB常用命令1——数据库操作
本节介绍了 MongoDB 中数据库的选择、创建与删除操作。使用 `use 数据库名称` 可选择或创建数据库,若数据库不存在则自动创建。通过 `show dbs` 或 `show databases` 查看所有可访问的数据库,用 `db` 命令查看当前数据库。注意,集合仅在插入数据后才会真正创建。数据库命名需遵循 UTF-8 格式,避免特殊字符,长度不超过 64 字节,且部分名称如 `admin`、`local` 和 `config` 为系统保留。删除数据库可通过 `db.dropDatabase()` 实现,主要用于移除已持久化的数据库。
75 0
|
1月前
|
存储 NoSQL MongoDB
从 MongoDB 到 时序数据库 TDengine,沃太能源实现 18 倍写入性能提升
沃太能源是国内领先储能设备生产厂商,数十万储能终端遍布世界各地。此前使用 MongoDB 存储时序数据,但随着设备测点增加,MongoDB 在存储效率、写入性能、查询性能等方面暴露出短板。经过对比,沃太能源选择了专业时序数据库 TDengine,生产效能显著提升:整体上,数据压缩率超 10 倍、写入性能提升 18 倍,查询在特定场景上也实现了数倍的提升。同时减少了技术架构复杂度,实现了零代码数据接入。本文将对 TDengine 在沃太能源的应用情况进行详解。
62 0
|
2月前
|
存储 NoSQL MongoDB
数据库数据恢复—MongoDB数据库迁移过程中丢失文件的数据恢复案例
某单位一台MongoDB数据库由于业务需求进行了数据迁移,数据库迁移后提示:“Windows无法启动MongoDB服务(位于 本地计算机 上)错误1067:进程意外终止。”
|
4月前
|
存储 JSON NoSQL
学习 MongoDB:打开强大的数据库技术大门
MongoDB 是一个基于分布式文件存储的文档数据库,由 C++ 编写,旨在为 Web 应用提供可扩展的高性能数据存储解决方案。它与 MySQL 类似,但使用文档结构而非表结构。核心概念包括:数据库(Database)、集合(Collection)、文档(Document)和字段(Field)。MongoDB 使用 BSON 格式存储数据,支持多种数据类型,如字符串、整数、数组等,并通过二进制编码实现高效存储和传输。BSON 文档结构类似 JSON,但更紧凑,适合网络传输。
112 15
|
4月前
|
存储 NoSQL 关系型数据库
阿里云数据库MongoDB版助力信也科技 打造互联网金融企业样板
我们的风控系统引入阿里云数据库MongoDB版后,解决了特征类字段灵活加减的问题,大大提高了开发效率,极大的提升了业务用户体验,获得了非常好的效果
阿里云数据库MongoDB版助力信也科技 打造互联网金融企业样板
|
5月前
|
NoSQL Cloud Native atlas
探索云原生数据库:MongoDB Atlas 的实践与思考
【10月更文挑战第21天】本文探讨了MongoDB Atlas的核心特性、实践应用及对云原生数据库未来的思考。MongoDB Atlas作为MongoDB的云原生版本,提供全球分布式、完全托管、弹性伸缩和安全合规等优势,支持快速部署、数据全球化、自动化运维和灵活定价。文章还讨论了云原生数据库的未来趋势,如架构灵活性、智能化运维和混合云支持,并分享了实施MongoDB Atlas的最佳实践。
|
6月前
|
NoSQL Cloud Native atlas
探索云原生数据库:MongoDB Atlas 的实践与思考
【10月更文挑战第20天】本文探讨了MongoDB Atlas的核心特性、实践应用及对未来云原生数据库的思考。MongoDB Atlas作为云原生数据库服务,具备全球分布、完全托管、弹性伸缩和安全合规等优势,支持快速部署、数据全球化、自动化运维和灵活定价。文章还讨论了实施MongoDB Atlas的最佳实践和职业心得,展望了云原生数据库的发展趋势。
下一篇
oss创建bucket