Retrieving Data from MongoDB

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.

Sample Database

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

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

Connecting to the Database

We start a mongod process from the command line, passing our database directory.

mongod --dbpath=dbdirname

Then, in our server.js file, we are going to create a connection to the server and our database mydb.

CloseCopy Copied
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');

Populating the Grid

We want to be able to fetch the documents in the users collection to use in our grid. To do so, we will create a route path at /mydb, which has the array of documents.

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

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

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

We run our server from the command line with:

CloseCopy Copied
node server.js


Customizing the Grid

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

CloseCopy Copied
<zing-grid src="http://localhost:3000/mydb">
    <zg-column index="name"></zg-column>


Join the Community

Support, extra demos, pre-releases and more