0% found this document useful (0 votes)
4 views

Unit 5

Uploaded by

kakago7436
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit 5

Uploaded by

kakago7436
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Unit 5

What is node js?

Node.js is an open-source, cross-platform JavaScript runtime environment that executes


JavaScript code outside of a web browser. It allows developers to use JavaScript for server-
side scripting, enabling the development of scalable network applications. Node.js is built on
the V8 JavaScript runtime engine, which is the same engine that powers Google Chrome.

Key features of Node.js include:

Asynchronous and Event-Driven: Node.js is designed to be asynchronous and event-driven,


making it well-suited for handling concurrent operations. It uses an event loop to efficiently
manage I/O operations without blocking the execution of other tasks.

Single-Threaded: While JavaScript traditionally runs in a single-threaded environment,


Node.js uses an event-driven, non-blocking I/O model to handle many connections
simultaneously. This allows Node.js to efficiently manage numerous concurrent connections.

NPM (Node Package Manager): Node.js comes with a built-in package manager called NPM,
which provides a vast ecosystem of open-source libraries and tools that developers can use
in their projects. NPM simplifies dependency management and allows easy sharing of code
among developers.

Server-Side Development: Node.js is commonly used for building server-side applications,


APIs (Application Programming Interfaces), and microservices. It is particularly well-suited for
real-time applications like chat applications, online gaming, and collaborative tools.

Cross-Platform: Node.js is designed to run on various operating systems, including Windows,


macOS, and Linux, making it a versatile choice for developers working in different
environments.

Community and Ecosystem: Node.js has a large and active community of developers, which
contributes to its vibrant ecosystem. This community support results in a wide range of
modules and packages available through NPM, covering a broad spectrum of functionalities.

What is a mongoose?
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a
straightforward, schema-based solution to model application data and interact with
MongoDB databases using JavaScript. Mongoose sits on top of the MongoDB Node.js driver
and simplifies the process of working with MongoDB by adding a layer of abstraction and
additional features.

Key features of Mongoose include:

Schema Definition: Mongoose allows developers to define a schema for their data, specifying
the structure, data types, and validation rules for each field in a document. This schema
provides a clear and consistent structure for the data stored in MongoDB.

Model Creation: Mongoose allows you to create models based on defined schemas. Models
are constructor functions that provide an interface for interacting with a specific MongoDB
collection. They encapsulate the behavior and structure of the documents within that
collection.

CRUD Operations: Mongoose simplifies the process of performing CRUD (Create, Read,
Update, Delete) operations on MongoDB. It provides convenient methods for inserting,
querying, updating, and deleting documents in a MongoDB collection.

Middleware: Mongoose supports middleware functions that allow developers to execute


custom logic before or after specific events, such as validation, saving, updating, or removing
documents. This enables the implementation of additional business logic or data processing.

Query Building: Mongoose provides a rich set of methods for building complex queries.
Developers can use these methods to filter, sort, and project data from MongoDB in a way
that is more expressive and readable than using raw MongoDB queries.

Population: Mongoose supports population, a feature that allows developers to reference


documents in other collections and automatically retrieve the referenced data when
querying. This helps in simplifying data retrieval and reducing the need for multiple queries.

Validation: Mongoose provides built-in validation for data based on the defined schema. This
ensures that data adheres to the specified rules before being saved to the database.

Connection Management: Mongoose simplifies the management of database connections,


including connection pooling and handling connection events. It also supports connection to
multiple MongoDB databases.

How Mongoose works with Nodejs


Step 1: Install Mongoose

npm install mongoose

Step 2: Set Up Connection

Create a file (e.g., app.js) and set up the Mongoose connection:

const mongoose = require('mongoose');

// Connection URI

const uri = 'mongodb://localhost:27017/your-database-name'; // Update with your MongoDB


server details and database name

// Connect to MongoDB

mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });

// Get the default connection


const db = mongoose.connection;

// Bind connection to error event

db.on('error', console.error.bind(console, 'MongoDB connection error:'));

db.once('open', () => {

console.log('Connected to MongoDB');

// Perform CRUD operations here

// Close the connection when done

mongoose.connection.close();

});

Step 3: Define a Model

Define a Mongoose schema and model for your collection:

const mongoose = require('mongoose');

// Define a schema

const personSchema = new mongoose.Schema({

name: String,

age: Number,

});

// Create a model

const Person = mongoose.model('Person', personSchema);

// Example usage

const newPerson = new Person({ name: 'John Doe', age: 30 });

// Save the document

newPerson.save((err, savedPerson) => {

if (err) {

console.error('Error saving document:', err);


return;

console.log('Document saved:', savedPerson);

});

Step 4: CRUD Operations

Perform CRUD operations using the Mongoose model:

Create (Insert) Operation:

// Insert a document

const newPerson = new Person({ name: 'John Doe', age: 30 });

newPerson.save((err, savedPerson) => {

if (err) {

console.error('Error saving document:', err);

return;

console.log('Document saved:', savedPerson);

});

Read Operation:

// Find documents

Person.find({ age: { $gte: 25 } }, (err, people) => {

if (err) {

console.error('Error finding documents:', err);

return;

console.log('Found documents:', people);


});

Update Operation:

// Update a document

Person.updateOne(

{ name: 'John Doe' },

{ $set: { age: 31 } },

(err, result) => {

if (err) {

console.error('Error updating document:', err);

return;

console.log('Document updated:', result.nModified);

);

Delete Operation:

// Delete a document

Person.deleteOne({ name: 'John Doe' }, (err, result) => {

if (err) {

console.error('Error deleting document:', err);

return;

console.log('Document deleted:', result.deletedCount);

});

You might also like