1673332497
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.
Timestamps:
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
Code: https://github.com/dejwid/mern-blog
Subscribe: https://www.youtube.com/@CodingWithDawid/featured
1668523680
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) {
console.log(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.
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:
collection.insertOne(
{
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.
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.
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.
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);
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:
client.close();
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:
Thank you for reading 😉
Original article source at: https://sebhastian.com/
1666949320
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.
https://tuts-station.com/how-to-connect-mongodb-database-to-django.html
1661829180
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))
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
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")
end
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.")
end
# Delete the document and ensure it is no more by counting
delete(cats, ("_id" => m_oid))
println(count(cats, ("name" => "Mokie")))
The command_simple
function allows broad access to MongoDB actions. For example, creating an index:
command_simple(client,
"db",
Dict(
"createIndexes" => "cats",
"indexes" => [
Dict(
"key" => Dict("name" => 1),
"name" => "cats_name",
"unique" => 1)
]
))
command_simple
returns a BSONObject
reply, so you can also perform aggregations:
command_simple(client,
"db",
OrderedDict(
"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 github.com and submit a pull request if you have a contribution you think is worthwhile!
Author: ScottPJones
Source Code: https://github.com/ScottPJones/Mongo.jl
License: View license
1661620197
bson
=========
Bson library for Dart programming language
Version 1.0.0 has breaking API changes. See changelog for details.
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
):
dependencies:
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.
Now in your Dart code, you can use:
import 'package:bson/bson.dart';
Download Details:
Author: mongo-dart
Source Code: https://github.com/mongo-dart/bson
1661409000
Gorilla's Session store implementation with MongoDB
Depends on the mgo library.
go get github.com/kidstuff/mongostore
Available on godoc.org.
func foo(rw http.ResponseWriter, req *http.Request) {
// Fetch new store.
dbsess, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer dbsess.Close()
store := mongostore.NewMongoStore(dbsess.DB("test").C("test_session"), 3600, true,
[]byte("secret-key"))
// Get a session.
session, err := store.Get(req, "session-key")
if err != nil {
log.Println(err.Error())
}
// 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")
}
Author: Kidstuff
Source Code: https://github.com/kidstuff/mongostore
License: BSD-3-Clause license
1660894320
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": [
"node_modules\\screepsmod-mongo\\index.js"
],
Start server!
DB Population
mongo.importDB()
in the screeps cli imports your existing DB
OR
system.resetAllData()
in the screeps cli for a completely fresh DB
Once done restart the server
Done!
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.
https://docs.mongodb.com/manual/tutorial/backup-and-restore-tools/
https://redis.io/topics/persistence
All options and defaults are listed below
If the uri Parameter is supplied it will overwrite all other settings. Use it for Authentication, passing extra options, etc.
Config can be applied in several ways:
Add to the bottom of your .screepsrc file
[mongo]
host = 192.168.0.222
[redis]
host = 192.168.0.222
Please note that this method only works when launching modules directly, when launched via the default launcher they will be ignored.
MONGO_HOST='192.168.0.222'
MONGO_CONN='mongodb://username:password@hostname.com/database_name?ssl=true'
Author: ScreepsMods
Source Code: https://github.com/ScreepsMods/screepsmod-mongo
License: MIT license
1660299780
The MongoDB supported driver for Go.
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 go.mongodb.org/mongo-driver
and having the build step install the dependency or by explicitly running
go get go.mongodb.org/mongo-driver/mongo
When using a version of Go that does not support modules, the driver can be installed using dep
by running
dep ensure -add "go.mongodb.org/mongo-driver/mongo"
To get started with the driver, import the mongo
package and create a mongo.Client
with the Connect
function:
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
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 {
panic(err)
}
}()
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 "go.mongodb.org/mongo-driver/bson"
to your imports.
Your import statement should now look like this:
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
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 {
log.Fatal(err)
}
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 {
log.Fatal(err)
}
// 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: https://jira.mongodb.org/browse/GODRIVER
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.
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
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 \
--tlsAllowInvalidCertificates
To run the tests with make
, set:
MONGO_GO_DRIVER_CA_FILE
to the location of the CA file used by the databaseMONGO_GO_DRIVER_KEY_FILE
to the location of the client key fileMONGO_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 fileMONGODB_URI
to the connection string of the serverAUTH=auth
SSL=ssl
For example:
AUTH=auth SSL=ssl \
MONGO_GO_DRIVER_CA_FILE=$PATH_TO_CA_FILE \
MONGO_GO_DRIVER_KEY_FILE=$PATH_TO_CLIENT_KEY_FILE \
MONGO_GO_DRIVER_PKCS8_ENCRYPTED_KEY_FILE=$PATH_TO_ENCRYPTED_KEY_FILE \
MONGO_GO_DRIVER_PKCS8_UNENCRYPTED_KEY_FILE=$PATH_TO_UNENCRYPTED_KEY_FILE \
MONGODB_URI="mongodb://user:password@localhost:27017/?authSource=admin" \
make
Notes:
--tlsAllowInvalidCertificates
flag is required on the server for the test suite to work correctly.?authSource=admin
, not /admin
.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:
MONGO_GO_DRIVER_COMPRESSOR=snappy make
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.
Commits to master are run automatically on evergreen.
See our common issues documentation for troubleshooting frequently encountered issues.
@ashleymcnamara - Mongo Gopher Artwork
Author: Mongodb
Source Code: https://github.com/mongodb/mongo-go-driver
License: Apache-2.0 license
1658250000
Small template with user authentication in Apollo Server.
MONGODB_URI=<YOUR MONGODB URI>
JWT_SECRET=<SECRET WORD>
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
or
npm run dev
Author: zclut
Source code: https://github.com/zclut/graphql-auth-template
License: MIT license
1626684671
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.
Subscribe: https://www.youtube.com/channel/UCDR79YG43mX3I8_75kyd3Kw/featured
#spring-boot #mongo #docker
1625885173
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: https://github.com/TylerPottsDev/mern-todo
Subscribe: https://www.youtube.com/c/TylerPotts/featured
#react #node #mongo
1621446240
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.
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
1618651236
https://www.facebook.com/groups/816378872626439
#mern #mean #react #javascript #mongo #nodejs
1618463445
#mongodb cloud #mongodb atlas cluster #mongodb #mongo
1616412060
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