diff --git a/Programming_Languages/NodeJS/REST_APIs/05__Integrating_the_database.md b/Programming_Languages/NodeJS/REST_APIs/05__Integrating_the_database.md index ffc2d00..4e3edf5 100644 --- a/Programming_Languages/NodeJS/REST_APIs/05__Integrating_the_database.md +++ b/Programming_Languages/NodeJS/REST_APIs/05__Integrating_the_database.md @@ -8,3 +8,71 @@ tags: [backend, node-js, REST, APIs, mongo-db] # Creating a RESTful API: Integrating the database So far we have set up the application and an `/api/courses` route which handles requests for RESTful API operations on a local array of course objects. We now want to have the endpoints operate on a MongoDB `courses` collection rather than the array. + +## Set-up + +We will follow the routine for establishing a MongoDB instance as detailed in [my notes](/Databases/MongoDB/Connect_to_database.md) on Mongo: + +- [Create MongoDB database](/Databases/MongoDB/Create_database.md) +- [Connect to MongoDB database](/Databases/MongoDB/Connect_to_database.md) + +Our `index.js` now looks like the following: + +```js +// index.js + +// Connect to database +mongoose + .connect("mongodb://127.0.0.1/playground") + .then(() => console.log("Connected to MongoDB")) + .catch((err) => console.error(err)); + +app.use(express.json()); + +// Link to `courses` route which contains our REST request handlers for this part of the API +app.use("/api/courses", courses); +``` + +## Integrating Mongo with our our `courses` module + +### Create the schema + +Now we go the router module for `courses` and start to use Mongoose, defining our `Course` schema: + +```diff +// index.js + +// Connect to database +mongoose + .connect("mongodb://127.0.0.1/playground") + .then(() => console.log("Connected to MongoDB")) + .catch((err) => console.error(err)); + +app.use(express.json()); + +// Link to `courses` route which contains our REST request handlers for this part of the API +app.use("/api/courses", courses); + ++ const courseSchema = new mongoose.Schema({ ++ name: {type: String, required: true, minlength: 5, maxlength: 255}, ++ author: String, ++ tags: [String], ++ data: {type: Date, default: Date.now}, // if unspecified, entry will default to current date ++ isPublished: Boolean, ++ }); + +``` + +### Create a model + +```diff +const courseSchema = new mongoose.Schema({ + name: {type: String, required: true, minlength: 5, maxlength: 255}, + author: String, + tags: [String], + data: {type: Date, default: Date.now}, // if unspecified, entry will default to current date + isPublished: Boolean, + }); + ++ const Course = new mongoose.model('Course', courseSchema); +```