Code  JS

Code JS


Build a Fullstack Blog App using MERN

In this tutorial, I'm going to show you how to build a fullstack blog app using MERN (mongo, express, react, node).

This blog app tutorial is designed for beginners and will teach you the basics of building a blog app using MERN. By the end of this tutorial, you will have a working blog app that you can use to publish your blog content.

00:00:00 - Intro
00:02:02 - Building homepage with react
00:23:35 - Routing with react-router-dom
00:34:50 - Login and register page
00:42:32 - Authentication
01:22:01 - Checking if logged in
01:30:38 - Logout functionality
01:33:05 - UserContext
01:41:04 - Create new post page
02:15:52 - Displaying posts from the database
02:38:26 - Single post page
03:02:20 - Edit post page
03:31:57 - Outro



#mern #javascript #mongo #react #node  

Build a Fullstack Blog App using MERN
Desmond  Gerber

Desmond Gerber


Why You Don't Need MongoJS Library for NodeJS Application

Learn the proper way to connect to a MongoDB library using NodeJS.

The mongojs npm package is a NodeJS module that implements the MongoDB native driver in NodeJS. The purpose of the package is to help JavaScript developers to connect their NodeJS instance to their MongoDB instance.

But with the release of the official MongoDB driver for NodeJS, the mongojs package is now obsolete and it’s recommended for you to use mongodb package instead.

The mongodb NodeJS driver comes with asynchronous Javascript API functions that you can use to connect and manipulate your MongoDB data.

You need to install the mongodb package to your project first:

npm install mongodb
# or
yarn add mongodb

Once installed, you need to import the MongoClient class from the library as follows:

const { MongoClient } = require("mongodb");

Then, you can connect to your MongoDB database by creating a new instance of the MongoClient class and passing the URI as its argument:

const uri = "mongodb+srv://<Your MongoDB atlas cluster scheme>";

const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,

If you’re installing MongoDB locally, then you can connect by passing the MongoDB localhost URI scheme as shown below:

const client = new MongoClient("mongodb://localhost:27017", {
  useNewUrlParser: true,
  useUnifiedTopology: true,

Then, connect to the database using the client.connect() method as shown below:

client.connect(async (err) => {
  if (err) {
  const collection = client.db("test").collection("animals");
  // perform actions on the collection object

Almost all MongoDB API methods will return a Promise object when you don’t pass a callback function to the methods.

This means you can use either the callback pattern, the promise chain pattern, or the async/await pattern when manipulating your collection’s data.

See also: Wait for JavaScript functions to finish using callbacks and promises

Here’s how to use the connect() method using the async/await pattern. Don’t forget to wrap the code below inside an async function:

try {
  await client.connect();
  console.log(`connect OK`);

  const collection = client.db("test").collection("animals");
  // perform actions on the collection object
} catch (error) {
  console.log(`connect error: ${error}`);

Once connected, you can choose the database you want to connect with by calling the client.db() method and specify the database string as its argument:

const db = client.db("test");

You can also choose the collection you want to manipulate by calling the db.collection() method and specify the collection string as its argument:

const db = client.db("test");
const collection = db.collection("animals");

The db() and collection() method calls can be chained for brevity.

Once a connection has been established to the MongoDB instance, you can manipulate the database using methods provided by MongoDB library.

Inserting documents to a MongoDB collection

To insert a document to your MongoDB collection, you can use either insertOne() or insertMany() method.

The insertOne() method is used to insert a single document into your collection object. Here’s an example of the method in action:

await collection.insertOne({
  name: "Barnes",
  species: "Horse",
  age: 5,

Or when using callback pattern:

    name: "Barnes",
    species: "Horse",
    age: 5,
  (err, result) => {
    // handle error/ result...

When using insertMany() method, you need to wrap all your object documents in a single array:

await collection.insertOne([
    name: "Barnes",
    species: "Horse",
    age: 5,
    name: "Jack"
    species: "Dog",
    age: 4,

Next, let’s look at finding documents in your collection.

Finding documents in a MongoDB collection

To find documents inside your MongoDB collection, the library provides you with the findOne() and find() method.

Here’s how to use them:

const doc = await collection.findOne({ name: "Barnes" });
console.log('The document with { name: "Barnes" } =>', doc);

// or

const filteredDocs = await collection.find({ species: "Horse" }).toArray();
console.log("Found documents =>", filteredDocs);

To retrieve all documents available in your collection, you can pass an empty object {} as the parameter to your find() method call:

const docs = await collection.find({}).toArray();
console.log("All documents =>", docs);

To query by comparison, you need to use the built-in Comparison Query Operators provided by MongoDB.

For example, the following find() call only retrieve documents with age value greater than 2:

const filteredDocs = await collection.find({ age: { $gt: 2 } }).toArray();
console.log("Found documents =>", filteredDocs);

Next, let’s look at how you can update the documents.

Updating documents in a MongoDB collection

You can update documents inside your collection by using the updateOne() or updateMany() method.

The update query starts with the $set operator as shown below:

{ $set: { <field1>: <value1>, <field2>: <value2>, ... } }

For example, the code below updates a document with name:"Barnes" to have age: 10:

const updatedDoc = await collection.updateOne(
  { name: "Barnes" },
  { $set: { age: 10 } }
console.log("Updated document =>", updatedDoc);

When there is more than one document that matches the query, the updateOne() method only updates the first document returned by the query (commonly the first document inserted into the collection)

To update all documents that match the query, you need to use the updateMany() method:

const updatedDocs = await collection.updateMany(
  { species: "Dog" },
  { $set: { age: 3 } }
console.log("Set all Dog age to 3 =>", updatedDocs);

Now let’s see how you can delete documents from the collection.

Deleting documents in a MongoDB collection

The deleteOne() and deleteMany() methods are used to remove document(s) from your collection.

You need to pass the query for the delete methods as shown below:

const deletedDoc = await collection.deleteOne({ name: "Barnes" });
console.log('Deleted document with {name: "Barnes"} =>', deletedDoc);

// or

const deletedDocs = await collection.deleteMany({ species: "Horse" })
console.log("Deleted horse documents =>", deletedDocs);

Closing your MongoDB connection

Finally, when you’re done with manipulating the database entries, you need to close the Database connection properly to free your computing resource and prevent connection leak

Just call the client.close() method as shown below:


And that will be all for this tutorial.

For more information, visit the official MongoDB NodeJS driver documentation and select the API documentation for your current version from the right side menu:

MongoDB API documentations

MongoDB API documentations

Thank you for reading 😉

Original article source at:

#node #mongo #npm 

Why You Don't Need MongoJS Library for NodeJS Application

How to Connect MongoDB Database to Django? -

How to Connect MongoDB Database to Django?

Hi Dev,

I am going to show you example of how to connect mongodb database to django. I would like to show you how to connection mongodb database with django. if you have question about how to connect a django app to mongodb with djongo then I will give simple example with solution. you will learn how to connect a django app to mongodb with mongoengine.

Let's imagine that you are engaged in a real-time project. You must work with unstructured data that contains millions of records. MongoDB enters the scene at this point. It can easily store and read unstructured data. Now that we have a foundational understanding, let's look more closely at MongoDB and Django.

  • MongoEngine
  • PyMongo
  • Djongo

#django #python #mongo 

How to Connect MongoDB Database to Django? -

Mongo.jl: Mongo Bindings for The Julia Programming Language


MongoDB bindings for The Julia Language


Building this package should build and/or install the MongoDB C driver for you.


You must have a MongoDB server running somewhere. You can specify the host and port in the MongoClient constructor, otherwise it uses the Mongo default locahost:27017.

using Mongo, LibBSON

# Create a client connection
client = MongoClient() # default locahost:27017

# Get a handle to collection named "cats" in database "db".
# Client object, database name, and collection name are stored as variables.
cats = MongoCollection(client, "db", "cats")

# Insert a document
# Mokie is a pretty old cat
m_oid = insert(cats, Dict("name" => "Mokie", "age" => 17))

Dictionary Syntax

With MongoDB, documents and queries are represented as BSONObject structures. In Julia, we can create these from Associative data structures like Dict. However, most functions in this package also accept a Union{Pair,Tuple} in lieu of that, allowing us to omit the Dict constructor:

# Pebbles is an even older cat
p_oid = insert(cats, ("name" => "Pebbles", "age" => 19))

# Ensure they were inserted by counting
println(count(cats, ("name" => "Mokie"))) # 1
println(count(cats)) # 2

Query Syntax

MongoDB queries are also BSON documents, and can include certain modifiers and operators which allow for the construction of complex queries. This package includes shortcut functions for many of them so, for instance instead of typing:

Dict("\$query" => Dict("age" => Dict("\$lt" => 19)))

We can do the following:

# Print all cats under age 19
for doc in find(cats, query("age" => lt(19)))
    println("$(doc["name"]) is younger than 19")

Operators and modifiers can be combined by encasing them in parenthesis.

# It's Mokie's birthday!
# We can use the shortcut for the "$inc" operator to increase Mokie's age by 1
update(cats, ("_id" => m_oid), inc("age" => 1))

for doc in find(cats, (query(), orderby("age" => 1)))
    println("$(doc["name"]) is $(doc["age"]) years old.")

# Delete the document and ensure it is no more by counting
delete(cats, ("_id" => m_oid))
println(count(cats, ("name" => "Mokie")))

Command Syntax

The command_simple function allows broad access to MongoDB actions. For example, creating an index:

                  "createIndexes" => "cats",
                  "indexes" => [
                          "key" => Dict("name" => 1),
                          "name" => "cats_name",
                          "unique" => 1)

command_simple returns a BSONObject reply, so you can also perform aggregations:

                  "aggregate" => "cats",
                  "pipeline" => [
                      Dict("\$match" => Dict("age" => 19)),
                      Dict("\$group" => Dict("_id" => "\$name", "count" => Dict("\$sum" => 1)))

Refer to the MongoDB database commands docs for further commands.


Contributions are welcome! Please fork on and submit a pull request if you have a contribution you think is worthwhile!

Download Details:

Author: ScottPJones
Source Code: 
License: View license

#julia #mongo 

Mongo.jl: Mongo Bindings for The Julia Programming Language

Bson Library for Dart Programming Language



Bson library for Dart programming language

Version 1.0.0 has breaking API changes. See changelog for details.

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add bson

With Flutter:

 $ flutter pub add bson

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

  bson: ^1.0.4

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:bson/bson.dart'; 

Download Details:

Author: mongo-dart

Source Code:

#mongo #dart #programming 

Bson Library for Dart Programming Language

Mongostore: Gorilla's Session Store Implementation with MongoDB


Gorilla's Session store implementation with MongoDB


Depends on the mgo library.


go get


Available on


    func foo(rw http.ResponseWriter, req *http.Request) {
        // Fetch new store.
        dbsess, err := mgo.Dial("localhost")
        if err != nil {
        defer dbsess.Close()

        store := mongostore.NewMongoStore(dbsess.DB("test").C("test_session"), 3600, true,

        // Get a session.
        session, err := store.Get(req, "session-key")
        if err != nil {

        // Add a value.
        session.Values["foo"] = "bar"

        // Save.
        if err = sessions.Save(req, rw); err != nil {
            log.Printf("Error saving session: %v", err)

        fmt.Fprintln(rw, "ok")

Download Details:

Author: Kidstuff
Source Code: 
License: BSD-3-Clause license

#go #golang #mongo #store 

Mongostore: Gorilla's Session Store Implementation with MongoDB
Lawrence  Lesch

Lawrence Lesch


Screepsmod-mongo: Replace LokiJS with MongoDB and Redis


MongoDB And Redis for the Screeps Private Server 



Installing on Ubuntu? Check out the community guide in the official Docs Private server on Ubuntu using MongoDB and Redis or the newer screeps-launcher guide Newbie-friendly (ish) private/dedicated server setup guide for Ubuntu 18.04, with automatic startup

Ensure both mongodb and redis are already installed and running

npm install screepsmod-mongo inside your server's mods folder

Ensure the mod has been added to mods.json. Eg:

 "mods": [

Start server!

DB Population

mongo.importDB() in the screeps cli imports your existing DB


system.resetAllData() in the screeps cli for a completely fresh DB

Once done restart the server



With this mod installed you can continue to manage the server as usual, all CLI commands behave identically. The original storage module will still run, but is completely ignored.

Keep in mind that RAM requirements are slightly higher, by default mongo uses 50% - 1G of your system RAM. Redis on the other hand, uses very little.

Mongo and Redis CLIs can be used to see and modify the data as usual, backups and restores should be done via normal mongo and redis tools.


All options and defaults are listed below


  • host: localhost
  • port: 27017
  • database: screeps
  • uri: mongodb://localhost:27017/screeps

If the uri Parameter is supplied it will overwrite all other settings. Use it for Authentication, passing extra options, etc.


  • host: localhost
  • port: 6379


Config can be applied in several ways:

.screepsrc (Recommended)

Add to the bottom of your .screepsrc file

host =

host =

ENV Method

Please note that this method only works when launching modules directly, when launched via the default launcher they will be ignored.


Download Details:

Author: ScreepsMods
Source Code: 
License: MIT license

#javascript #mongo #redis #mongodb 

Screepsmod-mongo: Replace LokiJS with MongoDB and Redis

Mongo-go-driver: The Go Driver for MongoDB

MongoDB Go Driver

The MongoDB supported driver for Go.


  • Go 1.10 or higher if using the driver as a dependency. Go 1.17 or higher if building the driver yourself. We aim to support the latest versions of Go.
  • MongoDB 2.6 and higher.


The recommended way to get started using the MongoDB Go driver is by using Go modules to install the dependency in your project. This can be done either by importing packages from and having the build step install the dependency or by explicitly running

go get

When using a version of Go that does not support modules, the driver can be installed using dep by running

dep ensure -add ""


To get started with the driver, import the mongo package and create a mongo.Client with the Connect function:

import (


ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))

Make sure to defer a call to Disconnect after instantiating your client:

defer func() {
    if err = client.Disconnect(ctx); err != nil {

For more advanced configuration and authentication, see the documentation for mongo.Connect.

Calling Connect does not block for server discovery. If you wish to know if a MongoDB server has been found and connected to, use the Ping method:

ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err = client.Ping(ctx, readpref.Primary())

To insert a document into a collection, first retrieve a Database and then Collection instance from the Client:

collection := client.Database("testing").Collection("numbers")

The Collection instance can then be used to insert documents:

ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
res, err := collection.InsertOne(ctx, bson.D{{"name", "pi"}, {"value", 3.14159}})
id := res.InsertedID

To use bson.D, you will need to add "" to your imports.

Your import statement should now look like this:

import (


Several query methods return a cursor, which can be used like this:

ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cur, err := collection.Find(ctx, bson.D{})
if err != nil { log.Fatal(err) }
defer cur.Close(ctx)
for cur.Next(ctx) {
    var result bson.D
    err := cur.Decode(&result)
    if err != nil { log.Fatal(err) }
    // do something with result....
if err := cur.Err(); err != nil {

For methods that return a single item, a SingleResult instance is returned:

var result struct {
    Value float64
filter := bson.D{{"name", "pi"}}
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err = collection.FindOne(ctx, filter).Decode(&result)
if err == mongo.ErrNoDocuments {
    // Do something when no record was found
    fmt.Println("record does not exist")
} else if err != nil {
// Do something with result...

Additional examples and documentation can be found under the examples directory and on the MongoDB Documentation website.


For help with the driver, please post in the MongoDB Community Forums.

New features and bugs can be reported on jira:

Testing / Development

The driver tests can be run against several database configurations. The most simple configuration is a standalone mongod with no auth, no ssl, and no compression. To run these basic driver tests, make sure a standalone MongoDB server instance is running at localhost:27017. To run the tests, you can run make (on Windows, run nmake). This will run coverage, run go-lint, run go-vet, and build the examples.

Testing Different Topologies

To test a replica set or sharded cluster, set MONGODB_URI="<connection-string>" for the make command. For example, for a local replica set named rs1 comprised of three nodes on ports 27017, 27018, and 27019:

MONGODB_URI="mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs1" make

Testing Auth and TLS

To test authentication and TLS, first set up a MongoDB cluster with auth and TLS configured. Testing authentication requires a user with the root role on the admin database. Here is an example command that would run a mongod with TLS correctly configured for tests. Either set or replace PATH_TO_SERVER_KEY_FILE and PATH_TO_CA_FILE with paths to their respective files:

mongod \
--auth \
--tlsMode requireTLS \
--tlsCertificateKeyFile $PATH_TO_SERVER_KEY_FILE \
--tlsCAFile $PATH_TO_CA_FILE \

To run the tests with make, set:

  • MONGO_GO_DRIVER_CA_FILE to the location of the CA file used by the database
  • MONGO_GO_DRIVER_KEY_FILE to the location of the client key file
  • MONGO_GO_DRIVER_PKCS8_ENCRYPTED_KEY_FILE to the location of the pkcs8 client key file encrypted with the password string: password
  • MONGO_GO_DRIVER_PKCS8_UNENCRYPTED_KEY_FILE to the location of the unencrypted pkcs8 key file
  • MONGODB_URI to the connection string of the server
  • AUTH=auth
  • SSL=ssl

For example:

AUTH=auth SSL=ssl \
MONGODB_URI="mongodb://user:password@localhost:27017/?authSource=admin" \


  • The --tlsAllowInvalidCertificates flag is required on the server for the test suite to work correctly.
  • The test suite requires the auth database to be set with ?authSource=admin, not /admin.

Testing Compression

The MongoDB Go Driver supports wire protocol compression using Snappy, zLib, or zstd. To run tests with wire protocol compression, set MONGO_GO_DRIVER_COMPRESSOR to snappy, zlib, or zstd. For example:


Ensure the --networkMessageCompressors flag on mongod or mongos includes zlib if testing zLib compression.


Check out the project page for tickets that need completing. See our contribution guidelines for details.

Continuous Integration

Commits to master are run automatically on evergreen.

Frequently Encountered Issues

See our common issues documentation for troubleshooting frequently encountered issues.

Thanks and Acknowledgement

@ashleymcnamara - Mongo Gopher Artwork

Download Details:

Author: Mongodb
Source Code: 
License: Apache-2.0 license

#go #golang #mongo #driver 

Mongo-go-driver: The Go Driver for MongoDB
Jillian  Corwin

Jillian Corwin


Small Template with User Authentication in Apollo Server.

GraphQL Auth Template

Small template with user authentication in Apollo Server.

Author :man_technologist:

Environment :gear:


Installation and Usage 💻

To install the dependencies we will locate ourselves in the repository folder and execute the following command:

npm install

To start the server we will execute the following command:

npm start 
npm run dev

Author: zclut
Source code:
License: MIT license

#apollo #graphql #mongo 

Small Template with User Authentication in Apollo Server.
Coding  Life

Coding Life


Create RESTful API in Spring Boot Mongo DB with Docker | Java Spring boot MongoDB REST API

In this tutorial we are going to create RESTful API in spring boot mongo DB with the help of docker will install mongo DB and will use VSCode editor and Will learn about new extensions like how to manage java projects in VS Code.


#spring-boot #mongo #docker

Create RESTful API in Spring Boot Mongo DB with Docker | Java Spring boot MongoDB REST API
Bryan JS

Bryan JS


Build a Fullstack app with React, Express, Node & Mongo MERN STACK

In today’s video we learn how to build a fullstack Todo app using React JS, Express JS, NodeJS and Mongo DB, also known as the MERN Stack.

Source code: 


#react #node #mongo

Build a Fullstack app with React, Express, Node & Mongo MERN STACK
Sigrid  Farrell

Sigrid Farrell


Spring Data: Data Auditing Using JaVers and MongoDB

Recently I was looking for some simple options to track all changes to entities in all my microservices. After researching, I discovered the Java library named JaVers. It is designed as a framework for auditing changes in object-oriented data.

In this post, we’ll see how to use JaVers in a simple Spring Boot application and MongoDB environment to track changes of entities.


  • Spring Boot 2.
  • Maven 3.6.1.
  • JAVA 8.
  • Mongo 4.4.

What is JaVers

JaVers is an audit log framework that helps to track changes of entities in the application.

The usage of this tool is not limited to debugging and auditing only. It can be successfully applied to perform analysis, force security policies and maintaining the event log, too.

#java #spring boot #maven #spring data #mongo #audit tracking

Spring Data: Data Auditing Using JaVers and MongoDB



MERN Stack Developer

#mern #mean #react #javascript #mongo #nodejs

 MERN Stack Developer
Ismael  Stark

Ismael Stark


Integrating MongoDB with Flask Using Flask-PyMongo

Building a web app almost always means dealing with data from a database. There are various databases to choose from, depending on your preference.

In this article, we shall be taking a look at how to integrate one of the most popular NoSQL databases - MongoDB - with the Flask micro-framework.

There are several Flask extensions for integrating MongoDB, here we’ll be using the Flask-PyMongo extension.

We will also be working on a simple Todo-List API to explore the CRUD capabilities of MongoDB

#python #flask #mongo

Integrating MongoDB with Flask Using Flask-PyMongo