fabiochiu/medium-articles huggingface dataset:
Setup MongoDB instance as Replica Set
By: Subham Majavadiya
Tags: Mongo, Master Slave, Scaleup, High Availability, Mongodb

In a production environment, we always want the System to be reliable and available every time and we could say data captured/processed by the system is one of the key aspects to achieve reliability and availability. One way to achieve data availability will be keeping a copy of data at multiple places, so if any time things go south we could recover the data as per need.

MongoDB provides an inbuilt mechanism to achieve data replication, by setting up a replica set between multiple MongoDB servers.

In this article, I am going to discuss the process of setup mongod instance into a replica set in centos 7.

Setup MongoDB instance [Primary]

Add mongo-repo to yum repo of the system if not exist

sudo vi /etc/yum.repos.d/mongodb-org.repo

[mongodb-org-3.4]

name=MongoDB Repository

baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/

gpgcheck=1

enabled=1

gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc Verify mogno-repo added successfully or not in the system

yum repolist Install MongoDB

sudo yum install mongodb-org After installation verify the version of the MongoDB

mongo --version Add replica set config and enable the same

sudo vi /etc/mongod.conf

replication:

repSetName: “rs0” Start MongoDB server

sudo systemctl start mongod Connect to mongo shell & run the following commands

mongo

rs.initiate()

After the primary instance setup is completed now create a secondary MongoDB instance by following steps 1 to 4 and then step 6 to start.

Also do make sure both primary and secondary server reachable to each other

Add Instance to Replica Set [Secondary]

Connect to the replica set primary instance, note that only the primary instance can add a new instance in the replica set. If you do not know which member is the primary, log into any member of the replica set and issue the db.isMaster() command. Use rs.add() to add the new instance to the replica set. Pass the member configuration document to the method. For example, to add a member at host mongodb3.local.net , issue the following command:

rs.add( { host: “mongodb3.local.net:27017”, priority: 0, votes: 0 } ) Verify that the new instance has reached SECONDARY state. To check the state of the replica set members, run rs.status()

Verify replication

Connect to master instance and insert/update data to any DB/collection. Connect to any SECONDARY node, verify the updated data.

If you have found this article useful hit the clap button to recommend it to others.
1. Express Js CRUD Tutorial using mongodb.(create)
By: Safaetul Ahasan
Tags: Expressjs, Nodejs, Mongodb

Create model:

vim user_model.js =======================code==================

const { Schema, model } = require('mongoose') //New Schema toiri kori

const userSchema = new Schema({

title:{

type: String,

required: true,

trim: true

},

description: {

type: String,

required: true,

trim: true

}

}) const user_table = model('user_table',userSchema)//create user_table module.exports = user_table

2. Create form:

vim home.ejs ====================code==========================

<!doctype html>

<html lang="en">

<head>

<link href=" https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css " rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> </head>

<body>

<h1>Hello, world!</h1> <form action="/user_create" method="POST">

<input type="text" name="title">

<textarea name="description"></textarea>

<input type="submit" class="btn btn-success" value="Submit">

</form>



</body>

</html>

3. Create Controller:

vim homeController.js ==================code========================= const user_model = require('./user_model') exports.createUserGetController = (req, res, next) => {

res.render('home')

} exports.createUserPostController = async (req, res, next) => {

//console.log(req.body)

//res.send(req.body) let {title,description,options} = req.body let user = new user_model({

title,

description

}) try{ await user.save() //save data,async for await

res.redirect('/') } catch (e) {

console.log(e)

} }

app.js
Care Amarillo Provider System
By: Christopher Coffee
Tags: React, Nodejs, Amarillo, Austin Coding Academy, Mongodb

The first open-source distributed system for local providers.

Intro

In little old Amarillo, Texas at the new Amarillo College Code Academy, my classmates and I created a system which will be used initially for local shelters. The idea is that the system will be managed by your local government. The admin will create the shelter and user, then give the initial credentials to the manager of the provider. The provider can then change update their credentials and fill in information such as location, bed count, name, slogan, etc. The provider can look at graphs of their bed count data changing. The admin can look at graphs of data of all provider bed counts, any information that was updated and created by every user, and disable/hide managing users and shelters.

Technologies Used

We created the frontend using React.js and the backend using Node.js. There is some code clean up and folder restructuring needed, which I plan to implement soon, and possibly document those changes. Here are the technologies we used to develop this app. I also plan to document how to set up the project.

Mailgun

Mailgun is an email service. We mainly use it to send the password reset email. It’s pretty easy to set up. This is a backend package.

Axios

We use Axios to make http requests on the frontend and backend.

Recharts

We use Recharts to show graph information about the shelter.

Intro.js-react

We use a react wrapper for Intro.js to give users a guided experience inside the system.

Firebase

We use firebase to handle the push notifications

Google Maps Embed API

We use this to show the location of the provider and provide driving directions.

Google Maps Place Autocomplete API

We used this to allow managing users of providers to search for their entity on Google when updating their provider information, so they don’t have to fill out everything. It’s essentially the same search you would get when searching on Google Maps.

Material UI

We used Material UI for most of the frontend design of the application.

Redux

We used Redux for frontend state management.

React Toastr

We used this to show error and success messages on the frontend.

React Select

We used this for the frontend provider search on the homepage

Mongoose

Used this on the backend for MongoDB robustness

Passport

Used for authentication on the backend

UUID

We used this package on the backend to generate unique strings for password reset endpoints

Dotenv

Used to handle backend environment variables

Care Amarillo Repositories

You can find the repos for Care Amarillo here:
How to connect Express js with mongodb
By: Safaetul Ahasan
Tags: Nodemon, Expressjs, Nodejs, Mongoose, Mongodb

Prerequisite tutorial:

Install Nodejs:

version check:

node -v

2. Install express.js,mongoose,morgan and nodemon

express.js(express js install)

mongoose(mongodb install)

morgan(for show log)

nodemon(server restart when some change occur)

mkdir blog_expressjs

cd blog_expressjs

npm init -y //Initialise and Configure Our Project

npm i express mongoose morgan

npm i -D nodemon //server restart when some change

3. package.json

Add ‘“start”: “nodemon app.js”

{

"name": "blog_expressjs",

"version": "1.0.0",

"description": "",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1",

"start": "nodemon app.js"

},

"keywords": [],

"author": "",

"license": "ISC",

"dependencies": {

"express": "^4.17.1",

"mongoose": "^5.11.8",

"morgan": "^1.10.0"

},

"devDependencies": {

"nodemon": "^2.0.6"

}

}

When I will write the following command ‘’npm start’’ than ‘’npm nodemon app.js’’ will be run.

4. app.js

const express = require('express')

const morgan = require('morgan') //medillower function

const mongoose = require('mongoose') const express = require('express')

const morgan = require('morgan') //medillower function

const mongoose = require('mongoose') const app = express() //route handaling,controller,templet engine,middleware app.use(morgan('dev')) //middleware

app.use(express.urlencoded({extended: true})) // for get form data

app.use(express.json()) app.get('/', (req, res) => {

console.log("peyas")

res.send("peyas")

}) mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true})

.then(() => { app.listen(4545, () => {

console.log('Connected')

})

})

.catch(e => {

console.log(e);

})

Mongoose official website.(use this following tool we can easily connect with mongodb).

sudo systemctl status mongodb

mongodb-compass

5. Run your project:
How to Install MongoDB on Mac
Tags: Setup Mongodb Macos, Install Mongodb, Mongodb Macos, Mongodb

Run the following command in your macOS Terminal

Step 1 — Install Homebrew

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Paste the above code (from the Homebrew website) in your terminal.

Then find the MongoDB tap

brew tap mongodb/brew

Step 2 — Install MongoDB

It might happen that Brew will ask you to install some other dependencies before installing mongodb-community , in that case brew will inform you the commands to run , also try this brew install wget , to get the necessary dependencies.

You can also run brew update and brew help , to be sure all is well with Brew.

brew install mongodb-community

MongoDB is now installed

Step 3— Create the Data Folders to Store Databases

You need to create the /data/db folder in System/Volumes/Data .

Use this command :

sudo mkdir -p /System/Volumes/Data/data/db

Give permissions:

sudo chown -R `id -un` /System/Volumes/Data/data/db

While typing your password in terminal , Asterisk’s will not be visible, so just type the correct password and press enter.

Step 4 — Using MongoDB

Starting MongoDB :

brew services run mongodb-community

Checking if MongoDB is running :

brew services list

The Mongo Shell :

If MongoDB is running, you should be able to access the Mongo shell with the mongo command.

mongo

Use ‘exit’ to exit out of Mongo Shell.

Stopping MongoDB :

brew services stop mongodb-community

Reference : MongoDB Manual
mLab Heroku Add-on shutdown & lost the database?
By: Liftoff Llc
Tags: Heroku Addon, Mlab, Recover Lost Db, Heroku, Mongodb

Are you one of those developers who didn’t get notified or missed the deadline of mLab add-on being terminated by Heroku on November 10th & your application is down?

Don’t worry, we have been there at LiftOff LLC & were able to successful recover the database & bring the application back online after few weeks in Dec.

We had a product developed in 2015 that was deployed on Heroku with mLab MongoDB add-on, that was created with customer’s email as owner of the app & all the notifications about mLab shutdown on Heroku was being sent to customer, then the app went down on Nov 11th. We were notified after a week or so saying the app is down :(

We didn’t have any backups outside of mLab servers but still able to recover the database, restore the web application in Dec 1st week. Follow the below steps if you need to do the same.

Step #1 — recover your username on mlab.com

When you provisioned the mLab MongoDB addon on, it would have created an account for you on mLab.com with a random password. Goto https://mlab.com/remind-usernames/ & enter the email address of the owner of the app on Heroku, it would send you the user name

Step #2 — reset the password for the mlab.com account

Now that you have the username on mlab.com reset the password for the same by visiting https://mlab.com/reset-password/ & set yourself a new password from the link that comes to the email address

Step #3 — login & request for an extension

mLab is being acquired by MongoDB.com & hence the Heroku add-on & their service is being terminated, and the good part is termination for mLab.com is Jan 21st 2021, that is the window you have to recover your database. mLab offers an option in dashboard to request an extension upto 30 days or so, you need to request for an extension.

Step #4 — revoke the DB login access

Once the extension is approved, do remember to take the database backup & revoke the database login access, if you don’t remember the password of the previous login create a new account. Now you are all set to grab the new connection string, change the ENV in Heroku to bring the app back up!

Step #5 — do migrate the database to MongoDB Atlas

You have a 30 days window to migrate from mLab.com to MongoDB Atlas, pick the right plan & move out the database

Hope this helps you, we definitely came back from the dooms day back into life for the product, that is actually rarely used but founder is keeping alive with a hope of selling the IP / product to another company & needs the app for doing demos.
First of all, very good article.
By: Jonathan Barone
Tags: Mongodb Atlas, Mongodb

First of all, very good article. You explained well the technical challenges you faced, and the compromises of the solutions.

About “join multiple collections” & “updating same data in many places, I faced the exact same problem when I started designing my backend for my side project. I was considering DynamoDB, and I spent many hours searching on this topic and there was no satisfying solution, it’s either data inconsistency or reads cost much more and are slower.

So I went on using MongoDB instead, together with Node.JS through the amazing Mongoose library.

I would recommend everyone looking for NoSQL backend to spin up a MongoDB instance (Atlas offers 500mg in their free tier), that “join multiple collections” challenge is included out of the box, just need to declare your relationships while defining your schemas.

Happy coding!
How to make a movie recommender: making a application using Svelte, FastAPI, MongoDB & TensorFlow Serving
By: Juan Domingo Ortuzar
Tags: Fastapi, TensorFlow, Machine Learning, Svelte, Mongodb

Hello, we are going to make a web application to make recommend movies. In this application a user will be able to write the title of a movie or more and the application will return a list of movies as a recommendation. Making this project you will learn how to make a movie recommendation engine, a REST API and a front-end reactive application. This tutorial will be divided into several parts so you can learn what you want. The code for the project is here.

This article is made to give you an idea of what are we going to make and the tools we are going to use. Lets start with a diagram of the different parts and the interaction with out application.

So we need to make a front-end application that the user will interact, then we have a back-end API that will process and coordinate the database and the AI model. Then we have a Database to save the movies and the AI model

So simple, now we know that we will be using movie names to show the user. Now lets think about the technology stack we are going to use:

Could you choose another technology stack, of course, you can choose whatever you want. Lets see what each of these tools we will be using for:

Svelte: a JavaScript framework for creating reactive application. Think of a smaller more reactive version of React, VueJS or Angular. This is going to be our front end, the place where the user is going to interact with our application.

TensorFlow: a Machine Learning/Artificial Intelligence framework created by Google for creating and training ML/AI models, we will be using the python version of TensorFlow. Also we will be using TensorFlow Serving to be able to make HTTP request to our trained Model.

MongoDB: its a NonSQL database engine, it means you can save anything you want in any way you want as long as it can be made into a dictionary. Since we are not going to use relationship tables it will be better. You can use a SQL database engine if you want, like SQLite or MySQL.

FastAPI: a REST API framework written in python, think of Django but great for prototyping and making faster API. I love this framework because it is very easy to create new endpoints and it abstract a lot of the harder things.

Docker: its a environment container framework. This means that you can make your code a package called containers, that can communicate with other containers without having to worry about dependencies or “cross contamination” between services.

How we will do it

I have divided each part of the recommender into a different section, so you can start whenever you want, just click on the links. But the recommended order is the following:

A couple of final words

This is by no way a production ready application nor is the only way to create movie recommender. This is a simple tutorial to create a demo application that uses Machine Learning and to show all the different parts and concepts that goes into creating a full stack application. I just want to share what I’ve learned.
Authentication Using Passport-Google-OAuth in Node.js
By: Harsh Mittal
Tags: Google Oauth, Authentication, Expressjs, Nodejs, Mongodb

Web Applications usually need a user to register on their application. So, Google authentication is a very important and safest way to register the user on the application. Here we’ll implement google-auth for user registration using the passport-google-oAuth library. This library combines passport-google-oauth1 and passport-google-oauth20.

Before Writing Code Developers needed to authenticate with google to get the clientId and clientSecret. It can be set from Google Developers Console. Developers also need to enable Google+API in the developer console, Otherwise, applications are unable to fetch user data from Google.

Node Modules Used

npm install passport

npm install passport-google-oauth

oAuth 1.0

The Google OAuth 1.0 authentication strategy authenticates users using a Google account and OAuth tokens. The strategy requires a verify callback, which accepts these credentials and calls done providing a user, as well as options specifying a consumer key, consumer secret, and callback URL.

Configuration

Routes

Link

A Link or button can be placed on the login form, allowing a one-click sign-in with google

<a href="/auth/google"> SignIn With Google </a>

Conclusion

I hope this will help you with passport-google-oAuth using passport.js.

Be familiar with this authentication. If you have any queries or suggestions, feel free to leave your comment in the comment section below.

Thanks for reading
Mongoose: How to make the global schema settings working with the local settings?
By: Zhiguang Chen
Tags: Mongoose, Nodejs, Mongodb

https://mongoosejs.com/docs/plugins.html

This document introduces a way to register global schema settings by registering global plugins, but it does not mention the situation when there are both global settings and local settings exist, such as what is the registration order? how to chain the functions? etc. Here is my solution, but not sure if it meets the best practice.

For example, here I have a memberSchema with a toJSON setting to transform avatar object to avatar.file and return this string, also have a setting: virtuals:true

const memberSchema = new Schema({

avatar: {

type: imageSchema,

},

}); memberSchema.set('toJSON', {

virtuals:true, transform: (document, returnedObject) => {

returnedObject.avatar = returnedObject.avatar?.file;

},

});

So, this is the way I register a global schema setting to delete _id and __v but also keep the settings from memberSchema

// typescript mongoose.plugin((schema: Schema) => {

// Some other features, such as:

// schema.pre('remove', backup); set_toJSON(schema);

}); const set_toJSON = (schema: Schema) => {

// Clone the setting from schemas

const settings = { ...schema.get('toJSON') }; // Abstract transform function

const transform = settings.transform;

delete settings.transform; schema.set('toJSON', {

// It will be overridden

virtuals: false, transform: (document, returnedObject) => {

delete returnedObject._id;

delete returnedObject.__v; //Execute the transform function from schemas such as memberSchema

transform && transform(document, returnedObject);

}, // Attach the other settings, such as virtuals:true from memberSchema in this example.

...settings,

});

};

Now both transforms are working fine, also the local setting virtual:true overrides the global one!

Please leave a comment if you have any other solutions, or maybe there is even an official interface to use? Thanks!
Intro to mongoBD
By: Diana Ponce
Tags: Programming, Code, Database, Mongodb

Currently in the internship i’m doing I was given a task which involved me taking a look at their Backend for their application. I noticed It was completely different from what I learned at my bootcamp. They were using MongoDB. I had to learn this in so little time to get my task done on time. So this is an introduction to MongoDB.

MongoDB is an open source NoSQL database. It is a document-based database management system. which supports a storage format known as binary JSON. It is a list of key- value pairs which can be three types, a primitive value, an array of documents or a list of key value pairs. This makes it easy for applications to obtain and change data. To query these objects,we can set filters on the collections expressed as a list of key-value pairs.

MongoDB requires us to always use the correct type. If you give an integer value into a document, you have to query for it also with an integer.The database also supports indexes, It is possible to create ascending, descending, unique and geospatial indexes.

there’s a lot to mongoDB but it is simple to use, their documentation is very good and I recommend to go check it out, in the next article I will do a small tutorial using mongoDB.
Setup your cluster on MongoDb Atlas
By: Naxir Sheikh
Tags: React, Node, Mongodb

In this article we will know how to setup your cluster on MongoDb Atlas

If you want to use MongoDb cloud service then you have must MongoDb Atlas account

Complete Signup Form

Create your cluster form the wizard , from here you have to select cloud provider and region.

GCP, lowa (us-central1)

After the selection of cloud provider and region and your cluster name you can can see your cluster i.e

From the network access you have to add IP Address from where you are accessing the cluster

Add IP Address

Create Database user

Connect with your cluster, choose your connection method here i am going to choose mongo shell

Copy the connection string and paste on your terminal enter your user password you will be able to connect with your cluster , now you can see i have switched to db i.e mydatabsae

:)

I hope that you liked this article and if you do , don’t forget about commenting!!! See ya! : 😊
Connect Your Cluster with Node
By: Naxir Sheikh
Tags: Node, Mongodb

Hi, hope you have read my previous article in which i have write down the steps to make your cluster on MongoDb Atlas, if not then you can check it i.e Create your Cluster on MongoDb Atlas

In this article I will show you to connect your cluster and list down all the databases on Node JS application.

I am using MongoDb javascript driver.

const { MongoClient } = require(‘mongodb’);

You have to update username, password and your cluster url

const uri = “mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority”;

Here is an MongoClient to interact with our database

const client = new MongoClient(uri);

For more detail about MongoClient check it out

Type your .js file name with node in my case it is like this node main.js

Here is all the complete code.

const { MongoClient } = require(‘mongodb’); const main = async () => { const uri = “mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority”; const client = new MongoClient(uri); try { await client.connect(); await listDatabases(client); } catch (e) { console.error(e); } finally { await client.close(); } } main().catch(console.error); const listDatabases = async (client) => { databasesList = await client.db().admin().listDatabases(); databasesList.databases.map(db => console.log(` — ${db.name}`)); };

Output

I hope that you liked this article and if you do , don’t forget about commenting!!! See ya! : 😊
MongoDB版本控管設計模式
Tags: NoSQL, Collection, Schema, Mongodb

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Conectarse a MongoAtlas desde el CMD en Windows
By: Cristian Sotomayor
Tags: Mongo, Command Prompt, Windows 10, Command Line, Mongodb

MongoDB Enterprise Server Download

Download MongoDB Enterprise Server, which provides advanced security and performance options for the most demanding…
Instalación de Mongo DB
By: Christian N
Tags: Instalación, Mongo, Mongodb

MongoDB Community Download

Download the Community version of MongoDB’s non-relational database server from MongoDB’s download center.
Setup auto backup for MongoDB to Amazon S3 via crontab Ubuntu
By: Sayed Tauseef Haider Naqvi
Tags: S3, Ubuntu, Mongodb, Data, Backup

This step-by-step tutorial has been written for Ubuntu.

Tested on Ubuntu 18.04 LTS, MongoDB v4.4.2 and AWS version 1.18.69

As a result of following your server will:

Dump all MongoDB database Sync the backups with Amazon S3 Run the above command every night with a cron job

Step 1) Create a shell script to dump the database

cd ~

mkdir bash_scripts

cd bash_scripts

nano mongodb_backups.sh

Paste in the following script (replace your_db_name with database name before paste)

#!/bin/bash

CUR_YEAR=`date +%Y`

CUR_MONTH=`date +%b`

CUR_DAY=`date +%d`

CUR_TIME=`date +%H:%M:%S`

S3_PATH=$CUR_YEAR/$CUR_MONTH/$CUR_DAY/mongodump_$CUR_TIME

DEST=~/mongodb_backups/$S3_PATH

if [[ ! -e $DEST ]]; then

mkdir -p $DEST

elif [[ ! -d $DEST ]]; then

echo "$DEST already exists but is not a directory" 1>&2

fi

echo "Mongodb backup start in $DEST"

mongodump --host localhost:27017 --db your_db_name --out $DEST

You can change S3_PATH according to your use case if you change this it will apply in local dump sub-directory and s3. Help in date formats use Man7 Linux Date.

Change mongodump command arguments as per your use case. Help in mongodump commands use mongodump offical doc.

Here are some basic commands:

1. --gzip to compresses the output.

2. --collection your_collection_name to dump only this collection data

chmod the script so its can be executed
Domain Driven Database Design
By: Doug Rosenberg
Tags: Domain Driven Design, Tutorial, Nodejs, Uml, Mongodb

Domain Driven Database Design

The first video of our CodeBot 201 tutorial series walks you through defining a domain model for a Fantasy Football app, and using CodeBot to instantly transform the domain model into a complete MongoDB database and REST API:

This video will show you how in less than 3 minutes…which is about how long it takes for you to try it yourself.

In our example , your app can show video of the players scoring touchdowns in near real-time.

In this video we’ll follow the evolution of the TEAM object from a noun on a short problem domain description,

Team is an object in the problem domain

to a class on a domain model diagram,

A Team has an Owner and a Roster and a Schedule

to a Mongo DB collection with a NodeJS REST API (documented in Swagger),

Use the API to Create Teams, Read Teams, Update Teams…

and a client-side layer that makes accessing the API nice and straightforward.

You don’t need to call the API directly because CodeBot generates client-side code including usage samples

CodeBot is a complex product that does an incredible amount of work to simplify your life as a developer. Give it a try today!
Install MongoDb on Mac (Catalina)
By: Naxir Sheikh
Tags: React, JavaScript, Nodejs, React Native, Mongodb

Hi, in this article I will show you all the steps to install MongoDb on your mac i.e Catalina

Install Homebew

# Installs Homebrew

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Find the MongoDb Tap

brew tap mongodb/brew

Install MongoDB

brew install mongodb-community

Apple created new volume in Catalina due to security purposes

Create ‘/data/db’ folder

sudo mkdir -p /System/Volumes/Data/data/db

For Permissions

sudo chown -R `id -un` /System/Volumes/Data/data/db

Start MongoDb

brew services run mongodb-community

brew services run mongodb-community

Check if MongoDb Is Running

brew services list

It’s Running :)

Access MongoDb Shell

mongo

Stop! MongoDb

brew services stop mongodb-community

Stop!

I hope that you liked this article and if you do , don’t forget about commenting!!! See ya! : 😊
The Mongo Shell In Action!
By: Naxir Sheikh
Tags: Databsae, Nodejs, Mongodb

Hope you have read my previous article if not then you can read via this link

https://naxir-sheikh.medium.com/install-mongodb-on-mac-catalina-373b4ef8ce02

In this lil :P article I will show you how we can play with mongo shell!

:P

Mongo Db Version

mongo --version

v4.4.1

Mongo Shell

mongo

Mongo Shell

Add Item Via Mongo Shell

use naxir_medium db.characters.insertOne({ name: 'naxir' })



db.characters.insertOne({ name: 'naxir' })

Find Command

db.characters.find()

db.characters.find()

I hope that you liked this article and if you do , don’t forget about commenting!!! See ya! : 😊
Covid-19 tracker — Avishka dev
By: Avishka Dev
Tags: Nodejs, Reactjs, Express, Mongodb

This is COVID-19 tarcker. you can watch latest COVID-19 news and others Developed By avishka dev

https://covid19tracker-seven.vercel.app

Avishka Dev | Linkedin | GitHub | Twitter | Facebook
Hybrid-tenancy with MongoDB in .NET API — Part 01
By: Alex Alves
Tags: Code, Dotnet, Tenants, Architecture, Mongodb

Many times we have some situations that require our application to attend to many clients. In this context, we have some techniques to attend this, but we will talk about three architectural strategies:

Single-Tenant

This technique consists of providing all of the new infrastructure necessary to stand-up an application. So, this signifies that you create a new instance of applications, a new database, and all other necessary things.

Clearly, you can note that the new client wins a new and completely isolated application. But the cost to keep this is high, besides that, you have some difficulty to deploy this application, like to construct a pipeline of CI/CD.

Multi-Tenant

In this technique, all clients use the same application and the same database, but you can separate the logic by schema and/or using Foreign Keys. In this case, the volume of data in the database can be grown a lot, and the risk to share/leak out the same data is high too.

Hybrid-Tenant

This is, maybe, the best alternative. This technique uses the same application but uses a different database, according to the client. So, the risk to share/leak out the data is less than the previous technique, and it is possible to do a horizontal scale.

What do you need to evaluate?

According to Fernando Neiva Paiva in his article about the tenants, we think about seven points:

Security policy

Budget

Scalability and elasticity

Functional requirements

Operations

Customizations

For the next step, we will see how can we build an application to apply this technique!

See you later!

Go to Part 02
Expose mongodb to the internet from Winodws
By: Robin Mollah
Tags: Windows, Database, Mongodb

Install mongodb from the following the official mongodb website.

Go to the following location `C:\Program Files\MongoDB\Server\4.4\bin`

Open `mongod.cfg` in a text editor.

Look for `bindIp: ` field. The default value of the field is 127.0.0.1. Add 0.0.0.0

Added `0.0.0.0` to the bindIp field.

What 0.0.0.0 does?

Initially, the MongoDB is exposed to only 127.0.0.1 the network interface. 0.0.0.0 exposes the MongoDB server to all network interfaces.

Security Threat: An authentication system should be implemented because anyone will be able to connect to it using the default username and password. Follow this tutorial to create a user.

Restarting MongoDB server using the configuration file

Open the “Edit the system environment variables” window and add the following link to the Path variable: C:\Program Files\MongoDB\Server\4.4\bin

To kill the previously running MongoDB process run the following command:

taskkill \F \IM mongod.exe

Now run:

mongod --config "C:\Program Files\MongoDB\Server\4.4\bin\mongod.cfg"

Now, you can try to connect using the public IP address.
MongoDB + Mongoose
By: Maya Alexandera
Tags: React, Authentication, JavaScript, Oauth, Mongodb

This is a mongoose.

For my last post, I wrote about my experience with passport JS/Google OAuth.

Next on the list was to create a database to save user data. For this project, I decided to explore MongoDB, a schema-less database. The biggest difference I noticed with Mongo is that each entry can have its own unique set of properties. This is in direct contrast to SQL-based, or relational databases — whose entries must all have the same properties.

MongoDB Setup

Sign up with MongoDB if you don’t already have an account.

‘Create a Cluster’ — I selected the free sandbox version for now.

Create a new database user — a user/password is required to interact with Mongo . I named mine ‘testUser’.

. I named mine ‘testUser’. You will be provided a collections string, which will be used to connect with the database. Make the necessary adjustments as instructed, filling in the user/password/database name properties.

Copy/Paste “Collections String” into a secret file with a key of “mongoURI”

Mongoose

Mongoose is an optional library that makes interacting with the database easier. One thing to note is, even though MongoDB does not require all records of a collection to have identical properties, mongoose is different. Mongoose wants to know ahead of time what all the properties will be to a given ‘Model’ class. The next step in this process is to use mongoose to create our User model/userShema. A Schema is a mongoose object that defines all the properties and datatypes of a given collection.
Django와 MongoDB연결해서 Rest API 만들면서 문제점
By: Restart Programmer Hyeonproject
Tags: Djongo, Restapi, Django, Python, Mongodb

Hyeonproject/h_blog_backend

You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or…
Avishka Dev - MERN Stack project
By: Avishka Dev
Tags: Nodejs, Reactjs, Express, Mongodb

do yo want any web site or App development please contact me!

Avishka Dev |My Project |About Me | Linkedin | GitHub | Twitter | Facebook
Lecciones de un año con MongoDB
By: Flavio Aandres
Tags: Desarrollo De Software, JavaScript, Development, Bases De Datos, Mongodb

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Top 5️⃣ Popular 📅Databases in 2020
By: Anupam Haldkar
Tags: MySQL, Database, Postgresql, Ms Sql Server, Mongodb

What database Providers are currently the most popular ❓

Which database are gaining more attention to the users community ❓

📌 Hint — They are most likely to be open source and having huge user community.

Here comes the solution to the above solution in Descending way ⏬-

5️⃣ MongoDB -

MongoDB is NoSQL database. In this database, data is stored in the form of JSON or BSON (Binary JSON) files.

If 👉🏻you’ve involved with classic relational databases, It may seem a bit strange. But it can easily cope with modern applications. In a traditional database, processing of files could be difficult🤥.

26% people preferred MongoDB according to the developer surveyed by StackOverflow. In addition to this, 👩🏻‍💻tech giants like eBay, Adobe, and Google are using it.
Fedora 33 — Como instalar o MongoDB 4.4
By: Marcelo Albuquerque
Tags: Servidor Web, Fedora, Linux, Mongodb

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Rabbitmq example working with GoLang
By: Mehmet Kiliç
Tags: Golang, Rabbitmq, Consumer, Procurement, Mongodb

Hi everyone , I recently try to GoLang and I have been really excited it’s capabilities , mostly in terms of speed. So I would to share with you on simple example.



Let’s think , we have 10 device(connected car) , their send to data to our service.

We write db connection, struct , utils and exception classes before write producer and consumer service.

The data model that will be produce to us will be as follows

device.go

We write json parser for more comfortable handling on our data model.

json parser will be as follows

jsonUtil.go

exception class will be as follows

exception.go

Our project’s mongodb connection will be as follows. We should import mongodb dependency for use to our project

“go.mongodb.org/mongodriver/mongo”

“go.mongodb.org/mongo-driver/mongo/options”

mongoservice.go

We should import rabbitmq dependency for use to our project

import “github.com/streadway/amqp”

Let’s write producer and consumer classes now

producer.go

and we write consumer class

consumer.go

You can add all the classes we wrote above to your project from github as dependencies.

Import “github.com/mehmetklllc/go-project/go-custom-struct”

Let’s use now, all the code we wrote

testproduce.go

We are going to send 1 million data to ”mkilic” topic of RabbitMQ

Now is the time read for the data we sent to RabbitMQ .

testconsumer.go
Embedded Mongo for Spring Boot Integration Test
By: Wahyudi H. Hermawan
Tags: Java, Embedded, Integration Testing, Mongodb

After previously I wrote about embedded postgres for the spring boot integration test. In this article, I will continue writing for another embedded DB, MongoDB.

Let’s just get straight to it.

First: Dependency.

<dependency>

<groupId>de.flapdoodle.embed</groupId>

<artifactId>de.flapdoodle.embed.mongo</artifactId>

<version>2.2.0</version>

<scope>test</scope>

</dependency>

Second: Please go to my previous article: H2 Database as Embedded Postgres for Spring Boot Integration Test.

E…. WHAT?!

Umm.. yeah, forgive me for my laziness. But Bill Gates once said:

I will choose a lazy person to do a hard job,

Because a lazy person will find an easy way to do it.

— Bill Gates

Hahaha. No, seriously, because the demo code will be almost identical.

The only differences is the object, repository for the object (which i’m pretty sure you already knew how to code both :D) and the dependency we need. You don’t even need to add application.properties for this.

Yes, remember KISS, Keep It Simple and Sweet (no, I won’t write “Stupid”, I believe you are Smart.)

Have a good day, fellas.
What is Duck-typing in ruby ?
By: Ankita Singh
Tags: Ruby, Ruby on Rails, JavaScript, Duck Typing, Mongodb

What is Duck-typing in ruby ?

Duck Typing gives the tendency in Ruby to be less concerned with a class of an object and more concerned with what/which methods can be called on that object and what/which operations can be performed on the object.

We all know that, In Ruby- we don’t need to declare the variable types and methods. i.e, everything in a Ruby is an object. Every objects in ruby are independent to each others, hence they can be modified independently. You can add methods to an object on their basis.

Duck typing refers that- “ If an object walks and talks (functions) like a duck, then Ruby Interpreter treat that object as a Duck. “

Let’s consider the following example:

Duck-typing in Ruby

Above example is the simple example of “Duck-typing” in Ruby. If an object responds or acts like a String then, treat it as a String. Hence, We should treat every objects on the basis of their methods or functions which they define rather than the classes from they inherit or modules which they include.
How To Install MongoDB Compass
By: Safaetul Ahasan
Tags: NoSQL, Nosql Database, Database, Mongodb Compass, Mongodb

Download and Install Compass — MongoDB Compass

Select your operating system: To download Compass, you can use your preferred web browser. Open the downloads page…
Connect MongoDB ใน Cypress
By: Kitphon Poonyapalang
Tags: Cypress, Mongodb

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
The Story of a Mongo Collection
By: Adnan Ahmed
Tags: Programming, Indexing, Database, Mongodb

In my last company, we were having more than 70 small APIs and we were using MongoDB heavily. Apart from having ELK stack, we also had database level logging for all the incoming requests to some of the endpoints to track the requests and responses.

A few months ago, we were struck with a disaster, because of something foolish that was missed in the code reviews. One night we did a deployment and after doing the sanity checks on production, considering everything is fine, we all went home thinking that all is good.

After a few hours, I got a call from our DevOps team the website is down. After some digging, we found out that MongoDB is causing the issue; there is some newly created collection having huge amount of data.

I checked our codebase and it turned out that someone enabled the database level request logging to MongoDB for the “autocomplete” API call in search. So imagine 1500 users sitting on the website, searching for flights and each keystroke in the search is getting logged to the database.

The size of the collection had grown to around 600 GB and there was no space left on the server to store more data and the website went down. The quickest hack was to put the capping of 1 GB on the collection until the issue is resolved; we did that and the website was live again.

To avoid this issue in the future, and also ensuring indexes on the collection, apart from making our code review process stricter, we decided to build a cli tool to help us manage the MongoDB indexes, capping and other constraints. The tool was responsible for the below listed items:

Notify against any newly created collections that are not registered against the API in the cli tool.

Notify if the size of a collection increases the specified size.

Notify if the collection doesn’t have any index or cap on it.

Show the list of indexes currently applied to the collection.

We built and deployed this to production and the issue never happened again. We were getting notified of any new collections which were not registered, keeping an eye on the indexes and sizes of the collections.

I hope that you liked the article. Feel free to leave your questions and comments below.
The Complete Microservice Tutorial — [Part 1] Building User Service With GRPC, Node.JS, and MongoDB
By: Md Ahad Hasan
Tags: Microservices, JavaScript, Nodejs, Microservice Architecture, Mongodb

Proto

Let’s make a new directory Microservice-Demo and cd into it. The directory structure we will follow

MicroService-Demo

├── userService

│ ├── proto

│ │ ├── **/*.js

│ ├── node_modules

│ ├── api.js

│ ├── auth.js

| ├── .env

| ├── Dockerfile

│ ├── index.js

| ├── package.json

│ └── testClient.js

├── protos

│ ├── user

│ │ ├── user.proto

| docker-compose.yml

We are going to keep all our proto files outside of our NodeJS application so that it’s easier for us to use those in other services. If you are wondering what is a proto file, it is a new format introduced by Google to serialize data for API usage that needs to be compiled with protoc compiler. The compiler outputs the language generated files in the desired language and GRPC uses them to communicate between services. So let’s see the user.proto file.

The proto file is using proto3 syntax. We see that there are a couple of messages in this file representing request and response data. Then there is a service UserSvc defined that has four methods that leverage these messages. Essentially, these are four APIs that we would be building today. There is a way to load the proto file’s definition in runtime without compiling the file, but we are going to compile the file here because that would make our life much easier when we build other services. Let’s compile this proto file and store the results in userService/proto directory. Run the next command from the root Microservice-Demo directory.

grpc_tools_node_protoc \

--js_out=import_style=commonjs,binary:userService/proto/ \

--grpc_out=grpc_js:userService/proto \

--proto_path=./protos/user ./protos/user/*.proto
Aflux-Ecom Journey Part 1…
By: Rahul Das
Tags: Backend Development, Expressjs, Ecommerce, Nodejs, Mongodb

What’s up guys? Hope you all are doing fine. Today I am blogging about my project that I build for my Portfolio and ELEVATE LABs.

I am going to tell you about my journey on building this project and the challenges I faced. My Site is live now you can visit https://aflux-ecom.netlify.app/ to play with it.

This Project is built with MERN Stack which stands for MongoDB, Express, React and Nodejs.

I built this project with focus on the front end. But on this first part of the blog I will tell you about the Back end codes that I wrote.

Its an E-commerce right? so first I need to write codes to post products before that I needed to prepare my nodejs server.

I started with ‘npm init’ command on by git bash terminal on the server folder.

This initializes a file package.json and prepares nodejs environment .

I just filled the relevant fields that were needed and pressed enter.

After preparing the nodejs environment, it was time to install some packages namely “express, body-parser, jsonwebtoken , cors , dotenv, mongoose”.

I ran command “npm i express body-parser jsonwebtoken cors dotenv mongoose” and installed all the necessary packages that I would need for the backend server.

Then I created an index.js file where I wrote the following codes.

I used models and routes folder to separate the codes and keep it manageable.

now it was time to build a mongoose schema. Schema is basically like a format through which mongoose saves database to mongodb.

I build two schemas which are above. One is for Product and one is for User. Then I started writing codes in routes for uploading products.

I wrote the above code to start uploading the products. After uploading the products. I wrote get products code which is as below:

now to test the api I used POSTMAN which is a famous tool that developers use for checking routes requests.

As all was working fine I switched my concern into handling user sign up signin.

Here I used all the npm packages which I installed earlier. I use bcrypt to hash passwords. Hashing passwords help to save guard the user authentication details. I used jsonwebtoken which we will use later to save login state later in the react app. This pretty much the backend a very simple one.

Note: I did not build entire backend-api in one-go. The whole app has been built with coding front-end and backend simultaneously. Its for easier understanding of the back end codes that only Backend codes are being shown in the first part of the blog.

Thats it for the backend codes and now Lets move to the front end on the next blog :)