0

I'm fairly new to working on MEAN stack applications and am working on a pre-existing MEAN stack application, which used to display some information on a page after pulling it from a mongoDB database and post it in tabular form. The information still exists in the database, but somewhere along the line, the code stopped showing data on the page. Now, I get the following error in my npm log: "CastError: Cast to ObjectId failed for value "" at path "_id". I'm having a very hard time figuring out what went wrong. I even tried to include ngResources as a dependency in the serviceA.js code below, but made no difference.

To clarify, this question is trying to determine why a specific piece of code isn't working. The previous question with a similar error discusses how to convert a string to an objectID. That's not the issue here. What I'm struggling with is how to get the relevant data out of MongoDB altogether. It seems like the correct query isn't being executed and I'm trying to figure out why.

Appreciate some help. Here's my code:

Html code (from file codeA.html):

<tr ng-repeat="x in allX | offset: offsetValue | limitTo: itemsPerPage track by x._id">

Corresponding controller code (from aController.js):

aController.controller('aCtrl', ['$scope','$http', '$state', 'serviceA', function($scope, $http, $state, serviceA, $rootScope) {

  if ($state.current.name == 'codeA') {
    $scope.reqLoadingHash = {};
    var docs = ['doc_a', 'doc_b', 'doc_c'];
    serviceA.get({}, function (response) {
      $scope.allX = response.searchResult;
      angular.forEach($scope.allX, function(val, key) {
        var numDocs = 0;
        docs.forEach(function(prop) {
          if (val[prop]) {
            numDocs++;
          }
        });
        $scope.allX[key].numDocs = numDocs;
      });
      $scope.range();
    });
  }
}])

serviceA code:

(function() {
  'use strict';

  angular.module('routerApp')
    .factory('serviceA', serviceA);

  serviceA.$inject = ['$resource'];

  function serviceA($resource) {
    return $resource('/api/requestA/:ownerRequestId', {}, {
      getRequest: {
        method: 'GET',
        url: '/api/requestA/user/:userId/listing/:listingId'
      },
      update: {
        method: 'PUT'
      },
      delete: {
          method: 'DELETE'
      }
    });
  }
})();

Router code:

var Router = require("express").Router;
module.exports = function () {
  var router = new Router();
  router.route('/requestA/:ownerRequestId').get(function(req, res, next) {
        ownerRequest.findById(req.params.ownerRequestId)
            .populate('listing owner')
            .exec(function(err, ownerRequest) {
                if (err) {
                    return next(err);
                }

                res.json({searchResult: ownerRequest});
            });
    });
  return router;
}
coder101
  • 383
  • 4
  • 21
  • 1
    The "linked duplicate" is an "exact match" for your reported error and problem. You are submitting data in `req.params.ownerRequestId` which is **not a valid ObjectId format** which is why you get that exact message. Understand that and make sure you send a valid format, or change your mongoose schema accordingly so `_id` is not the default `ObjectId` type. Your own text: `Now, I get the following error in my npm log: "CastError: Cast to ObjectId failed for value "" at path "_id".` – Neil Lunn Mar 07 '19 at 02:41

1 Answers1

0

Error message 'CastError: Cast to ObjectId failed for value "" at path "_id' is from your mongoDB function findById(). This function expects ObjectId as the first parameter, but in your case, it is just empty string so it throws error.

In your angular controller, you don't pass ownerRequestId as a parameter when you call serviceA.get().

Jake Noh
  • 216
  • 1
  • 7
  • I'm lost. What I'm trying to do is have the controller use serviceA to retrieve all documents from the MongoDB collection "ownerRequest" and retrieve information pertaining to those documents on the webpage (through "ng-repeat = x in allX" in the html code.) To accomplish that, how would you modify the code? – coder101 Mar 07 '19 at 01:23
  • @user6860460 If you want to retrieve all documents, then you should use `find()` instead of `findById()`. You might want to have another API endpoint called `/ownerRequests` and inside of the server controller, you have `ownerRequest.find()` and pass the result to the client. – Jake Noh Mar 07 '19 at 04:16
  • Didn't solve the issue. There's something else that's wrong with the code which is preventing the service from being called altogether. I placed some console.log statements in the serviceA code (after "function serviceA($resource) { " and they don't even appear in the browser console. – coder101 Mar 07 '19 at 16:34
  • Check if the controller and the service are under the same module and they are loaded browser correctly. – Jake Noh Mar 07 '19 at 21:19