I have successfully created an api that sends JSON data to my AngularJS application. The backend reads the data from Mongodb (using the Mongoose package). The index method works like a charm (I'm using jsonp as my test environment is one server, with the backend & frontend running on different ports)
exports.index = function (req, res){
return ContactModel.find(function (err, contacts) {
if (!err) {
return res.jsonp(contacts);
} else {
return console.log(err);
}
});
}
The AngularJS portion looks like this:
$http({method: 'jsonp', url: 'http://host:1222/contacts?callback=JSON_CALLBACK'}).success(function(data, status, headers, config) {
$scope.contacts = data;
});
And later on I can happily access this data (e.g. {{ contact.name }} )
The problem is that when I try to view only one result, using findById:
exports.findById = function (req, res) {
return ContactModel.findById(req.params.id, function (err, contact) {
if (!err) {
return res.jsonp(contact);
} else {
return console.log(err);
}
});
}
My AngularJS ViewController looks as such:
function ViewController($scope, $http) {
$http({method: 'jsonp', url: 'http://host:1222/contacts/:id?callback=JSON_CALLBACK'}).success(function(data, status, headers, config) {
console.log("Data: " +data);
$scope.contact = data;
});
}
And it's invoked by:
<a href="#/contacts/{{ contact._id }}">{{ contact.name }}</a>
However, the error that I keep on receiving is:
{ message: 'Cast to ObjectId failed for value ":id" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: ':id',
path: '_id' }
Here's a sample from the database:
JSON_CALLBACK && JSON_CALLBACK([
{
"name": "Test User",
"_id": "51c5fde3ce36618e0c000003",
"__v": 0
}
]);
I have read quite a few articles about the "Cast to ObjectId failed for value ":id" at path "_id"" problem, but I don't get it...Do I need to create my own ID for lookups? In that case I'd have to introduce an auto_increment unique ID-ing schema, which is not recommended for MongoDB, therefore, can you please advise what I'd have to do to be able to query the data in the right way? Also, if you see any issues with my current implementation in terms of AngularJS, please let me know (I'm new to the topic.).
Update
This is how I do routing with AngularJS:
angular.module('contactmanager', ['filters']).
config(function($routeProvider) {
$routeProvider.
when('/', {controller:ListController, templateUrl:'list.html'}).
when('/contacts/:id', {controller:ViewController, templateUrl:'contact.html'}).
otherwise({redirectTo:'/'});
});
Update 2
Server side routing -- express:
var express = require("express");
var contacts = require("./contact");
var app = express();
app.get("/", contacts.index);
app.get('/contacts', contacts.index);
app.get('/contacts/:id', contacts.findById);
app.listen(1222);
I assume something is missing from here then....?