Next, create a database for storing movies. Each movie contains at least a title, a Cloudinary ID for a banner image, and another Cloudinary ID for a movie trailer. Follow the procedure below.
-
Go to the mLab s site, create an account, and open the Create Wizard page.
-
Click **SANDBOX **under Plan Type.
-
Click Continue.
-
In the AWS Region dialog box, click a region and then click Continue.
-
In the Final Details dialog box, type a name, for example,
miniflix
, in the DATABASE NAME text field and click Continue. -
Verify that the information displayed in the Order Confirmation dialog box is correct and then click Submit Order.
-
Create a user by returning to the home page (Dashboard), clicking the new database, and then clicking the Users tab.
-
Click Add database user and, in the dialog box that is displayed, fill in the text fields. Click CREATE.
Next, create a schema and model with the Mongoose library to interact with our database. To do this, use a middleware that connects and disconnects with the database every time you fetch or write to the database. Follow these steps:
-
Create a file named
db.js
with the following content in a folder calledmiddleware
:// ./middlewares/db.js var mongoose = require('mongoose'); const MovieSchema = new mongoose.Schema({ title: String, banner: String, trailer: String, created_at: Date, id: mongoose.Schema.ObjectId }) module.exports = { // Connect/Disconnect middleware connectDisconnect: (req, res, next) => { // Create connection using Mongo Lab URL // available in Webtask context mongoose.createConnection(req.webtaskContext.secrets.MONGO_URL); // Create a mongoose model using the Schema req.movieModal = connection.model('Movie', MovieSchema); req.on('end', () => { // Disconnect when request // processing is completed mongoose.connection.close(); }) // Call next to move to // the next Express middleware next() }, }
MovieSchema
is an instance on the Mongoose schema but configured to map to the objects you specified. -
Create the middleware and export it as a function called
connectDisconnect
. -
Create a database for the
mLab
database withmongoose.createConnection
. Note that you are using the webtask context to fetch the URL from the environment so you need not hard-code your credentials. -
Create a model with the connection and attach it to the request for access by the routes.
-
When the request ends, close the connection with
close
.