DEVELOPING A LOOPBACK REST API BACKEND : add Mongodb (PART 2/N)
In the previous post we ended with a Rest Api backend based on LoopBack with a nice schema description (of a customer entity) and hookpoints for injecting Update and insert logic in the server save pipeline.
So far, we worked with an in memory database. Let’s fix that and configure Loopback in such a way it uses a database. There are a lot of options: Sql Server, Oracle, PostGres, MySql en MongoDB.
Let’s try to learn something new and go for mongoDb.
you might have enjoyed the experience of installing NodeJs when reading my previous article. Also installing MongoDb is a joy.
Go to Mongodb and install it.
Run MongDb as a windows service
Although you can run Mongodb simply by running it from the command prompt, it’s much easier to install it once as a windows service.
From an elevated (so with admin permission) command prompt type the command you find in the mongodb documentation on configuring a windows service for MongoDb.
Install the Loopback connector for MongoDb
You are already familiar with Npm now, so run from the same application folder following command:
Npm install –save loopback-connector-mongodb –msvs_version=2013
Update datasource.json to replace the in memory database to mongoDb.
Locate the datasource.json file:
Use your new Integrated development environment called NotePad and update that file as follows:
The syntax is quite straightforward, the connector attribute changed to “mongodb” and we provided an url as the database connectionstring.
Run now the server: Slc run and open http://localhost:3000/explorer. do again a post and verify that there are data. You will notice now that the id field is nolonger an integer value but a GUID.
Verify that there are data in the database.
From a command prompt type
- use lbdemo
- show collecdtions
Mongo will start a mongo client interface
use lbdemo switched to the lbdemo database
show collections shows the collecdtions, you will notice a customer collection
db.customers.find() show nicely in Json format the customer you inserted via the Rest Explorer.
It is almost hilarious how few code changes (even not code, but a json config file) we had to make for connecting our Rest Api to a decent persistent store: MongoDb.
In a next article I connect a decent client : AngularJS.