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/
1597736283
Looking to build dynamic, extensively featured, and full-fledged web applications?
Hire NodeJs Developer to create a real-time, faster, and scalable application to accelerate your business. At HourlyDeveloper.io, we have a team of expert Node.JS developers, who have experience in working with Bootstrap, HTML5, & CSS, and also hold the knowledge of the most advanced frameworks and platforms.
Contact our experts: https://bit.ly/3hUdppS
#hire nodejs developer #nodejs developer #nodejs development company #nodejs development services #nodejs development #nodejs
1590057960
Overview
In this tutorial, you will learn how to install Node onto Ubuntu 19.04 Disco Dingo. We will cover installation from the default repositories and, for those wanting more recent releases, how to install from the NodeSource repositories.
Installing from Ubuntu
The Ubuntu 19.04 Disco Dingo repository includes NodeJS version 10.15. Like most packages found here, it certainly is not the most recent release; however, if stability is more important than features, it will be your preferred choice.
#nodejs #nodejs 10.x #nodejs 11.x #nodejs 12.x #nodejs 8.x
1623498517
AppClues Infotech is one of the leading NodeJS app development company in USA that offering excellent NodeJS development services for web app development. We provide customized and high-quality NodeJS app development services to clients for different industries with advanced technology and functionalities.
Our dedicated app developers have years of experience in NodeJS development and thus successfully deliver cost-effective and highly customized solutions using the robust JavaScript engine of NodeJS.
Why Choose AppClues Infotech for NodeJS Application Development?
• Fast App Development
• Real-Time Application
• JSON (JavaScript Object Notation) in your Database
• Single Codebase
• Lower Cost
• Built-in NPM Support
• Inexpensive Testing and Hosting
For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910
#top nodejs app development company in usa #nodejs web app development #nodejs development agency in usa #hire nodejs app developers in usa #custom nodejs app development company #best nodejs app development service company
1603068240
The main goal of this blog is to explain the “Architecture of Nodejs” and to know how the Nodejs works behind the scenes,
Generally, most of the server-side languages, like PHP, ASP.NET, Ruby, and including Nodejs follows multi-threaded architecture. That means for each client-side request initiates a new thread or even a new process.
In Nodejs, all those requests from the clients are handled in a single-thread using shared resources concurrently as It follows the “Single-Threaded Event Loop Model”.
Event-Loop programming is a flow control in an application-defined by events. The basic principle of Nodejs’s event-driven loop is implementing a central mechanism that hears for events and calls the callback function once an event is turning up.
Nodejs is an event-loop that implements a run-time environment model to achieve non-blocking asynchronous behavior runs on Google Chrome’s V8 engine.
#nodejs #nodejs-developer #nodejs-architecture #nodejs-tutorial #backend #javascript #beginners #event-loop
1591985940
Created a Realtime Chat Application Using NodeJs and SocketIO
#nodejs #nodejs and socketio #application