MVC - using Controller concept to insert data into MongoDB Atlas collection.
STEP 1: setup your MongoDB Atlas database...(see other documents for help for this) & get connection information.
STEP 1.1: I have a database called shoppingsite with a collection call customers that I am going to access. Currently I have only 2 documents in it
STEP 1.2: Basically you follow the directions the MongoDB Atlas console gives you when you specify you want to connect from NodeJS code in order to get the URI for connection to use in your program.
STEP 2) You will need to install the mongodb module in your project (step 2 below) by running in the terminal of your WebStorm NodeJS+Express project that you must create:
npm install mongodb
STEP 3) In your NodeJS+Express project add a directory called controllers and in there a file called database.js
Here is the directory structure of my NodeJS + Express project with the controllers directory with the database.js file
Here is the code ----Read the comments to understand what it does.
//Define some varibles needed for the database Controller functions |
STEP 3) In your NodeJS+Express index.js file where you have routing specify both "/" as the main new custoer form AND "/saveNewCustomer" which will call the controller function defined in STEP 2
this is not necessarily the entire index.js file but, what you need to add to it.
var express = require('express'); /* GET home page which will call index.ejs which will have the form to collect data. */
//########################################
|
STEP 4: Here is the Form to capture the new customer's data (name and email). NOTE - I put this in the main index.ejs which will be called with the path "/". It will invoke the "/saveNewCustomer" path
<!DOCTYPE html> |
Here is the result of USING the form to create a new customer, running on the local machine
Follow the steps to deploy to Google Cloud Run --> BUT, you must ALSO MODIFY the MongoDB Atlas so it is accesible by Google Cloud Run!!!! Not just your local machine IP address. READ MORE ON WHAT YOU MUST DO... But, once you have setup this connectivity (from servlerless cloud to mongodb) it will work as shown below.