Retrieving Data from MongoDB

In this guide, we'll walk you through how to retrieve data from MongoDB with Node/Express and incorporate it in your grid.

In the examples below, we are using MongoDB with Node and Express. We assume that you have MongoDB installed and are running a local instance of your database. If not, refer to the MongoDB Documentation.

For our example, we set up a database mydb, which has the collection users with 3 documents:

{ name: "Tim", age: 21 },
{ name: "Alice", age: 30 },
{ name: "Henry", age: 45 }

Connecting to the Database

From the command line, we'll start a mongod process and pass in our database directory, like so:

mongod --dbpath=<dbdirname>

Then, in our server.js file, we'll create a connection to the server and our database mydb, like so:

var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();

var url = 'mongodb://localhost:27017';

MongoClient.connect(url, function(err, client) {
  db = client.db('mydb');
});
Top

Populating the Grid

To fetch the documents in the users collection to use in our grid, we'll create a route path at /mydb, which has the array of documents.

app.get('/mydb', function(req, res) {
  db.collection('users').find({}).toArray(function(err, docs) {
    res.send(docs);
  });
})

Now in our HTML file, we can create our grid and set the src attribute to this URL to read from the database.

<zing-grid src="http://localhost:3000/mydb"></zing-grid>

Then, we'll run our server from the command line with:

node server.js
Top

MongoDB Grid

Here is our complete grid pulling in data from our MongoDB database:

Top

Customizing the Grid

By default, MongoDB adds an _id field for each document. If you don't want to include a certain field in your grid, you can specify this using <zg-colgroup> and <zg-column>. Below, we show only the name field of our documents:

https://app.zingsoft.com/demos/embed/DDRV8ONU
https://app.zingsoft.com/demos/embed/DDRV8ONU
Top

[data: MongoDB]