CRUD operations with Mongoose
One of many reasons why developers opt to use Mongoose instead of the official MongoDB driver for Node.js is that it allows you to create data structures with ease by using schemas and also because of the built-in validation. MongoDB is a document-oriented database, meaning that the structure of the documents varies.
In the MVC architectural pattern, Mongoose is often used for creating models that shape or define data structures.
This is how a typical Mongoose schema would be defined and then compiled into a model:
const PersonSchema = new Schema({ firstName: String, lastName: String, }) const Person = connection.model('Person', PersonSchema)
Note
Model names should be in singular since Mongoose will make them plural and lowercase them when saving the collection to the database. For instance, if the model is named "User", it will be saved as a collection named "users" in MongoDB. Mongoose includes an internal dictionary...