Unit 5
Unit 5
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.
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.
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.
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.
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 URI
// Connect to MongoDB
db.once('open', () => {
console.log('Connected to MongoDB');
mongoose.connection.close();
});
// Define a schema
name: String,
age: Number,
});
// Create a model
// Example usage
if (err) {
});
// Insert a document
if (err) {
return;
});
Read Operation:
// Find documents
if (err) {
return;
Update Operation:
// Update a document
Person.updateOne(
{ $set: { age: 31 } },
if (err) {
return;
);
Delete Operation:
// Delete a document
if (err) {
return;
});