How to Get Started with Mongoose
Table of Contents
- Introduction
- Add Mongoose Dependency to Node Package File
- Run NPM Command to Install
- Try It Out
- Best Practice
- Conclusion
Introduction
This article provides information to help you get started with Mongoose. Before you start, you must have NPM and MongoDB installed.
Add Mongoose Dependency to Node Package File
"dependencies": {
"express": "~4.0.0",
"mongoose": "3.8.12"
},
Run NPM Command to Install
npm install mongoose
Try It Out
Try looking at the following examples to write code:
-
NPM mongoose - NPM Package
-
http://mongoosejs.com/ - Official Mongoose website
Best Practice
After you have installed Mongoose and tried sample code, you'll wonder what the best practice is for implementation.
You could reference the following article (it has a file to download):
mongoose-connection-best-practice
Conclusion
I think the best approach is to keep all the MongoDB connection logic in one place, which handles connecting to MongoDB, closing the MongoDB connection when Node.js shuts down, error handling for MongoDB, and defining all the collections.
These should all be in one place. Then your Node.js code just requires that file and uses its functions for CRUD operations.