Provision and Configure a Database
Last updated
Last updated
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 called middleware
:
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 with mongoose.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
.