Previously we published data from a database by creating our own API. Now, let's build functionality to allow users to submit and store data. We will add two core elements:
Form submissions are sent as JSON data in the body of a POST request to an API endpoint, and saved to MongoDB Atlas. API Endpoints are defined by Express, using Prisma to communicate with the database.
When successful, we will log the submission to the console, and also refresh the data list below. NOTE: this demo implements the 'C' and 'R' of 'CRUD' (Create and Read) . We will deal with the 'U' and 'D' (Update and Delete) elsewhere.
This NodeJS App uses Express and Prisma to create API endpoints for Creating (POST) and Reading (GET). It assumes a MongoDB data collection.
- Run
npm installto install express and prisma. - Add your MongoDB connection string to the
.envfile (see.env.examplefor an example). - Be sure to include the name of the Database you want to connect to. For example, if your connection string is
mongodb+srv://username:password@cluster.abc.mongodb.net/MyDatabase, you would changeMyDatabaseto any database name of your choosing. - If you point to an existing database, you may wish to introspect the schema using the command
npx prisma db pull --force. - Alternately, you can start with a blank database, by pointing the connection string to a Database that doesn't exist yet (Mongo creates it automatically as soon as you refer to it).
- Run
npx prisma generateto create the Prisma Client based onschema.prisma. - Run
npm run startto lauch the app.
A typical iteration pattern here would be as follows:
- create form elements that fit your concept, each with a given
name - add the corresponding
nametoschema.prismaand save - re-generate the Prisma Client from the schema using
npx prisma generate - re-start the app using
npm run start - test that the form works as expected
- verify that data is saving by using MongoDB Compass.