MnongoDB provides it's native driver to work with our project at server side but it may be large amount of code or repetition in code but it's not the case with mongooses. In this article I am going to tell you how to get started with
mongoose
Mongoose is a Node.js package that gives you an interface to play with mongo database. It is very light weight
npm
package to use in our application. Mongoose has all sets of methods that help you to connect and access data stored in Mongo database.
Mongoose is an Object Data Modeling
(ODM)
library for MongoDB and Node.js. Mongoose.js provides an abstraction layer on top of MongoDB that eliminates the need to use named collections in native MongoDB driver. Mongoose makes MongoDBeasier to work
with MongoDB. Mongoose allow developers to enforce a specific schema of desired object at the application layer.
What Mongoose Do ?
- provides schema validation
- It manages relationships between data
- make MongoDB easy to use
Content of this blog
1. Installing and Requiring Mongoose
2. Connecting To MongoDB database
3. Defining Schema
4. Creating Model
5. Creating and Saving Instance
6. Reading from DB
7. Updating
8. Deleting
(1). Installing andRequiring Mongoose
- install Mongoose npm package in your project directory as dependency using below shown command in terminal.
npm install mongoose --save
- Require mongoose in your application using this syntax
(2). Connecting To MongoDB database
Syntex
mongoose.connect(<Database URI>);
Using connection URI of database we cane connect to database.
here test is Database name
-
You can get connection Instance by
const db = mongoose.connect;
db object is used to listen the events attached to it.
We can use any function method. so don't get confused๐ by seeing it.
(3). Defining Schema
- schema is a way to describe *structure of documents * in database.
Schema accepts only the following Datatype.
- String
- Number
- Date
- Boolean
- Buffer
- ObjectId
- Mixed
- Array
In above example some Schema validator are used.
(4). Creating Model
- Mongoose model provides an interface to the database for creating, querying, updating, deleting etc...
- Model is one type of definition of database collection using
collection name
andschema name
. - Collection Name must be in singular form
(5). Creating and Saving Instance
- We can save object in database using
save()
method on model.
(6). Reading from DB
- We can reed data from database using
find()
on model and also find document by it's id usingfindById()
Top comments (0)