0

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....?

1 Answer 1

2

I assume the message is server side by mongo?

The message means the value of the _id is :id and not 51c5fde3ce36618e0c000003 and of course the :id string is not a valid ObjectId

Edit: so the above is correct, in your Controller your ajax call is hitting this url: http://host:1222/contacts/:id?callback=JSON_CALLBACK your :id is not parameterized, its hardcoded and is passed as a value.

You need to interpret the value of it using $routeParams:

function ViewController($scope, $http, $routeParams) {
    var ajax_url = 'http://host:1222/contacts/' + $routeParams.id + '?callback=JSON_CALLBACK';
    $http({method: 'jsonp', url: ajax_url}).success(function(data, status, headers, config) {
      console.log("Data: " +data);
      $scope.contact = data;
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

ah actually I was asking for the server side routing of the express app
updated again, although I bet there's something missing as I don't have much routing going on via express.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.