Creating Documents: Model.create() and save()
Explore how to create MongoDB documents in a MERN backend using Mongoose methods Model.create() and new Model().save(). Understand schema validation, middleware hooks, error handling for duplicates, and proper API responses in building a CRUD API.
This lesson focuses on the create (C) step in CRUD. With the Express and Mongoose scaffolding from the previous lesson in place, the next step is to create MongoDB documents through the API. In a MERN backend, a POST request arrives with a JSON body; Express parses the body into req.body, a controller passes that data to a Mongoose model, and the model validates the data against the schema and writes the document to MongoDB. The API response confirms the created document.
Creating a document is where schema rules, validation, and middleware from the previous chapter finally execute against live data. The model is the entry point: it casts the payload to the schema’s types, runs validators, fires any pre('save') hooks, and only then sends the write to the collection.
Note: The product example is runnable. It opens a local connection to the seeded
ecommercedatabase, inserts a document, and returns the result, just as an API would.
To make the path concrete, the next visual should show a create request moving from client to controller to model to MongoDB and back.
That flow leads into the two creation methods Mongoose offers.
Two ways to create a document
Mongoose gives two routes ...