using mongodb with nodejs and angular js

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

This is a final part of the node angular and mongodb tutorial.

So far each part of the whole process has been shown by far. This is a part showing how the data would be pulled and shown to the angular based page.

Mind you, in this tutorial, the page was getting the list from the hard coded array and that is simply changed to the array that is read from mongodb. That part can be hooked to other datasources like MsSQL server or MySQL or anything.

Using MongoDB in Node JS

1. Create a folder named node-mongo

2. install mongodb and express packages there

sudo npm install express
sudo npm install mongodb

*I will have another tutorial showing how to use the package manager using package.json. But for now just install the packages like the one I showed above.

3. create server.js in node-mongo folder and add the following content in it


var express = require('express');
var app = express();

//connection string for mongo
var mongoPath = "mongodb://localhost:27017/nodemongo";
//require mongo and get the client.
var mongoClient = require('mongodb').MongoClient;

//a router for the home page. "/" being the home page
app.get("/", function(request, response){
    response.sendFile(__dirname + "/views/home.html");
});

//a router for listening to /listcountries 
app.get("/listcountries", function(request, response){

    // mongo connection comes from here
    mongoClient.connect(mongoPath, function(error, database){
        var result = {};
        
        //once connected, then get the row from mongo database. find() would list all
        if (error) {
            result.message = "Connection error";
            response.send(result);
        } else {
            var collection = database.collection("countries");
            collection.find().toArray((err, listOfCountries)=>{
                response.send({"list":listOfCountries});
            });
        }
    });    
});

app.listen(8080);
console.log("serving web on port 8080");

By now, most of the usages on this file would be easy to understand if you have followed the previous tutorials.

How to install mongo in the computer and how to add some collections to it and the like is beyond the scope of this tutorial and I assume you have already installed mongo on your system and have created a database and collection with it.

In the example above, I have used mongo database named nodemongo and collection countries

4. create a folder views in node-mongo

5. create a file home.html and add the following code in in it


<html>
<head><title>Countries</title></head>
<body ng-app="NodeMongoApp">
<h2>here you would unleash the science of listing countries</h2>
<div ng-controller="MongoController">
    <a href="#" ng-click="listCountries()">list countries</a>

    <ul ng-repeat="country in countries">
        {{country.name}}
    </ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
    var app = angular.module("NodeMongoApp", []);
    app.controller("MongoController", function($scope, $http){
        
        $scope.listCountries = function() {
            $http.get("/listcountries").success(function(countries){
                $scope.countries = countries.list;    
            });
        };
    });
</script>
</body>
</html>

That is it.

Now you will want to be in the node-mongo folder and issue

node server.js

and from your browser, go to http://localhost:8080

You can download the whole project here

Fatal error: require(): Failed opening required Hydrator in mongodb

I was working on putting POPO to MongoDB in symfony project.
I have the Document inside BundleDocumentMyDocument.php

I want to create this document for the first time, but would like to update the document if it exists based on its two fields like:
* I have taken out some of additional information and focus on the main code only..

$file_id = getTheFileId();
$accessor_id = getAccessorId();
$repository=$this->getMongoService()
				->getManager()
				->getRepository('SomethinSomethingBundleDocumentFileAccess');
			$file_access=$repository->findOneBy(array('fileId'=>$file_id, 'accessorId'=>$accessor_id));
			if ($file_access && $file_access instanceof FileAccess){
				$file_access->setAccessCount($file_access->getAccessCount()+1);
			}else{
				$file_access=new FileAccess();
				$file_access->setFileId($file_id);
				$file_access->setAccessorId($accessor_id);
				$file_access->setAccessorType(FileAccess::ACCESS_TYPE_MEMBER);
				$file_access->setAccessDate(time());
				$file_access->setAccessCount(1);
			}
			$document_manager=$this->getMongoService()->getManager();
			$document_manager->persist($file_access);
			$document_manager->flush();

The problem I was facing was when I try to access the record, not when I was adding it.
and I know the record was there by using the command line mongo tool

The solution appears to be the missing config item for mongo:
on your config for mongo add

auto_generate_hydrator_classes: true

and that should fix the problem.

bundle does not contain any mapped documents/entities

This will be an error you would see when trying to generate entities or documents using:

app/console doctrine:mongodb:generate:documents YourPathToBundle

Actually the error would also suggest if you have mapping annotation error.

Mostly this could arise from mapping error as suggested.. check if you have @MongoDbDocument in the case of document or the respective @ORMEntity that would tell what that Plain Old Php Object is representing..
btw, the MongoDb and ORM are the aliases, so it could different on your setting..