Using MongoDB in Graphback
MongoDB is a general purpose, document-based, distributed database built for modern application developers. Graphback MongoDB Provider package provides instant integration to your Mongo database, giving you a full implementation of the CRUD API.
The package is built on top of the official MongoDB Node.js Driver.
#
InstallationInstall with npm:
Install with yarn:
Running either of the two commands will install the Graphback MongoDB Provider
(@graphback/runtime-mongo
) and the MongoDB Driver (mongodb
).
#
Creating Database ConnectionYou'll need a running MongoDB instance before initializing the connection.
info
If you do not have a running instance, you can use Docker to quickly spin up a MongoDB container by following the instructions given in MongoDB Docker Image.
The following code can be used to connect to your MongoDB.
Here we are connecting to the users
database, on a MongoDB instance running locally.
You can change the configurations variables to match the one you have.
To learn more about the accepted configuration, visit the MongoDB Driver Connection Options documentation.
#
Using MongoDB ProviderThe Graphback MongoDB provider exposes a createMongoDbProvider
method, which can be used to create data providers for each of your data models.
The code below shows how you can create such a data provider creator and how it can be passed to buildGraphbackAPI
.
The highlighted code does the following:
- Define connection URL to the MongoDB.
- Create a connection to our Mongo database.
- Select the
users
database. - And finally, create a data provider creator by using the
createMongoDbProvider
API.
The rest of the code uses buildGraphbackAPI
to create Graphback CRUD API based on the defined userModel
model.
Visit Data Models to learn more about how to design your business models.