The code for the example we are working with here can be accessed in the examples repository on GitHub.
Data modeling (in the context of databases and this tutorial) refers to the practice of formalizing a collection of entities, their properties and relations between one another. It is an almost mathematical process (borrowing a lot of language from set theory) but that should not scare you. When it comes down to it, it is exceedingly simple and quickly becomes more of an art than a science.
The crux of the problem of data modeling is to summarize and write down what constitutes useful entities and how they relate to one another in a graph of connections.
You may wonder what constitutes a useful entity. It is indeed the toughest question to answer. It is very difficult to tackle it without a good combined idea of what you are building, the database you are building on top of and what the most common queries, operations and aggregate statistics are. There are many resources out there that will guide you through answering that question. Here we'll start with the beginning: why is it needed?
Often times, getting the data model of your application right is crucial to its performance. A bad data model for your backend can mean it gets crippled by seemingly innocuous tasks. On the other hand, a good grasp on data modeling will make your life as a developer 1000 times easier. A good data model is not a source of constant pain, letting you develop and expand without slowing you down. It just is one of those things that pays out compounding returns.
Plus, there are nowadays many open-source tools that make building applications on top of data models really enjoyable. One of them is Prisma.
Let's walk through a example. We want to get a sense for what it'll take to design the data model for a simple message board a little like Reddit or YCombinator's Hacker News. At the very minimum, we want to have a concept of users: people should be able to register for an account. Beyond that, we need a concept of posts: some structure, attached to users, that holds the content they publish.
Using the Prisma schema language, which is very expressive even
if you haven't seen it before, our first go at writing down a
might look something like this:
In other words, our
User entity has properties
id (a database internal
createdAt (a timestamp, defaulting to now if not
specified, that marks the creation time of the user's account),
nickname (the user
specified display name, given on registration).
In addition, it has a property
posts which links a user with its posts through
Post entity. We may come up with something like this for the
In other words, our
Post entity has properties
id (a database internal
postedAt (a timestamp, defaulting to now if not specified,
that marks the time at which the user created the post and published it)
title (the title of the post);
authorId which specify a
one-to-many relationship between users and posts.
Let's look closer at these last two properties
authorId. There is
a significant difference between them with respect to how they are implemented
in the database. Remember that, at the end of the day, our data model will need
to be realized into a database. Because we're using Prisma, a lot of
these details are abstracted away from us. In this case,
the prisma code-generator will handle
@relation(...) attribute on the
author property is Prisma's
way of declaring that
authorId is a foreign key field. Because
the type of the
author property is a
User entity, Prisma
understands that posts are linked to users via
the foreign key
authorId which maps to the user's
associated primary key. This is an example of
a one-to-many relation.
Because our data model encodes the relation between posts and users, looking up a user's posts is inexpensive. This is the benefit of designing a good data model for an application: operations you have designed and planned for at this stage, are optimized for.
To get us started using this Prisma data model in an actual
application, let's create a new
npm project in an empty directory:
When prompted to specify the entry point, use
src/index.js. Install some nice
typescript bindings for node with:
Then you can initialize the typescript compiler with
This creates a
tsconfig.json file which configures the behavior of the
typescript compiler. Create a directory
src/ and add the following
Then create a
prisma/ directory and add a
schema.prisma file containing
the Prisma code for the two entities
Finally, to our
schema.prisma file, we need to add configuration for our local
dev database and the generation of the client:
Head over to the repository to see an example of the complete file, including the extra configuration.
To build the Prisma client, run
Finally, to run it all, edit your
package.json file (at the root of your
project's directory). Look for the
"script" field and modify the
Now all we need is for an instance of mongoDB to be running while we're working. We can run that straight from the official docker image:
To run the example do
You should see something close to the output of the snippet: our simple code failed because it is looking for a user that does not exist (yet) in our dev database. We will fix that in a little bit . But first, here's a secret.
Actually it's no secret at all. It is one of those things that everybody with software engineering experience knows. The key to writing good code is learning from your mistakes!
When coding becomes tedious is when it is hard to learn from errors. Usually
this is caused by a lengthy process to go from writing the code to testing it.
This can happen for many reasons: having to wait for the deployment of a backend
docker compose, sitting idly by while your code compiles just to fail at
the end because of a typo, the strong integration of a system with components
external to it, and many more.
The process that goes from the early stages of designing something to verifying its functionalities and rolling it out, that is what is commonly called the development cycle.
It should indeed be a cycle. Once the code is out there, deployed and running, it gets reviewed for quality and purpose. More often than not this happens because users break it and give feedback. The outcome of that gets folded in planning and designing for the next iteration or release. The agile philosophy is built on the idea that this cycle should be as short as possible.
So that brings the question: how do you make the development cycle as quick as possible? The faster the cycle is, the better your productivity becomes.
One of the keys to shortening a development cycle is making testing easy. When playing with databases and data models, it is something that is often hacky. In fact there are very few tools that let you iterate quickly on data models, much less developer-friendly tools.
The core issue at hand is that between iterations on ideas and features, we will need to make small and quick changes to our data model. What happens to our databases and the data in them in that case? Migration is sometimes an option but is notoriously hard and may not work at all if our changes are significant.
For development purposes the quickest solution is seeding our new data model with mock data. That way we can test our changes quickly and idiomatically.
At Synth we are building a declarative test data generator. It lets you write your data model in plain zero-code JSON and seed many relational and non-relational databases with mock data. It is completely free and open-source.
Let's take our data model and seed a development mongoDB database instance with Synth. Then we can make our development cycle very short by using an npm script that sets it all up for us whenever we need it.
We'll need the
synth command-line tool to get started. From a
Once the installer script is done, try running
to make sure everything works. If it doesn't work, add
$PATH environment variable with
and try again.
There is one main difference: the
synth schema is aimed at the
generation of data. This means it lets you specify the semantics of your data
model in addition to its entities and relations. The
has an understanding of what an email, a username, an address are; whereas the
Prisma schema only cares about top-level types (strings, integers, etc).
Each file we will put in the
synth/ directory that ends in
.json will be
synth, parsed and interpreted as part of our data
model. The structure of these files is simple: each one represents
a collection in our database.
To get started, let's create a
User.json file in the
Let's break this down. Our
User.json collection schema is a JSON object with
three fields. The
"type" represents the kind of generator we want. As we said
above, collections must generate arrays. The
fields are the parameters we need to specify an array generator.
"length" field specifies how many elements the generated array must have.
"content" specifies from what the elements of the array are generated.
For now the value of
"content" is a generator of the
null type. Which is why
our array has
null as a single element. But we will soon change this.
Note that the value of
"length" can be another generator. Of course, because
the length of an array is non-negative number, it cannot be just any generator.
But it can be any kind that will generate non-negative numbers. For example
This now makes our
users collection variable length. Its length will be
decided by the result of generating a new random integer between 5 and 10.
If you now run
you can see the result of that change.
synth fixes the seed of its
internal PRNG. This means that, by default, running
synth many times
on the same input schemas will give the same output data. If you want to
randomize the seed - and thus randomize the result, simply add the
Before we can get our
users collection to match
User Prisma model, we need to understand how to
generate more kinds of data with
Everything that goes into a schema file is a schema node. Schema
nodes can be identified by the
"type" field which specifies which kind of node
it is. The documentation pages have
a complete taxonomy of schema nodes and their
Let's look back at our
User model. It has four
Let's start with
id. How can we generate that?
The type of the
id property in the
and the attribute indicates that the field is meant to increment sequentially, going through values 0, 1, 2 etc.
What decides the variant is the presence of the
field in the node's specification.
For example, a
range variant would look like
constant variant would look like
Its type in the data model is that of a
synth schema type for
- and a lot more...
Since we are interested in generating email addresses, we will be using
"faker" variant which leverages a preset collection of
generators for common properties like usernames, addresses and emails:
Here is the finished result for our
Looking back at the
User model we started from, there's
one thing that we did not quite address yet. The
This means that, in our data model, no two users can share the same email
address. Yet, we haven't added that constraint anywhere in
What we need to use here is
modifiers. A modifier is an
attribute that we can add to any
synth schema type to modify the way it
behaves. There are two modifiers currently supported:
optional modifier is an easy way to make a schema node
randomly generate something or nothing:
unique modifier is an easy way to enforce the
constraint that the values generated have no duplication. So all we need to do,
to represent our data model correctly, is to add the
modifier to the
The completed end result for the
collection can be viewed on GitHub here.
Now that we have set up our
User.json collection, let's turn our attention to
Post model and write out the
synth schema for
Here is the end result:
It all looks pretty similar to the
User.json collection, except for one
important difference at the line
synth's way of
specifying relations between collections. Here we are creating
a many-to-1 relation between the field
Post.json collection and the field
id of the
schema can be viewed on GitHub here.
Now that our data model is implemented in Synth, we're ready to seed our test database with mock data. Here we'll use the offical mongo Docker image, but if you are using a relational database like Postgres or MySQL, you can follow the same process.
To start the mongo image in the background (if you haven't done so already), run
Then, to seed the database with
synth just run
That's it! Our test mongo instance is now seeded with the data of around 100 users. Head over to the examples repository to see the complete working example.
Synth is completely free and built in the open by an amazing and fast growing community of contributors.