Error: Failed to convert value "NaN" to ObjectId for the "_id" field

[ Issue resolved... the solution turned out to be surprisingly simple...

$scope.article = articleFactory.getArticles().get({id:parseInt($stateParams.id,10)}) .$promise.then(

should have been:

$scope.article = articleFactory.getArticles().get({
        id: $stateParams.id
    })

I did try this initially but Chrome was caching the old code - cleared history and problem solved.

Ouch.

]

Encountering an issue when transitioning my site from json-server to express / mongo / mongoose. Everything works on json, but upon moving to express / mongo / mongoose, I encounter the following error:

CastError: Cast to ObjectId failed for value "NaN" at path "_id" 

Resulting in a crash of the server...

The crash can be avoided by adjusting the route. Initially, it was configured as follows:

articleRouter.route('/:articleId')
.get(function (req, res, next) {
    Articles.findById(req.params.articleId, function (err, article) {
        if (err) throw err;
        res.json(article);
    });

})

Adding an if statement to filter out NaNs allows the server to run:

articleRouter.route('/:articleId')
.get(function (req, res, next) {

if (id.match(/^[0-9a-fA-F]{24}$/)) {
        Articles.findById(req.params.articleId, function (err, article) {
        if (err) throw err;
        res.json(article);
    });
}
})

However, it fails to serve "detail pages" where the id is passed. It's highly likely that this relates to data types within mongoose schemas, but being relatively new to this, I'm a bit lost.

The schema looks like this - with and without the id field:

var articleSchema = new Schema({
    _id: {
         type: String,
         required: true,
         unique: true,
         index: true
    },
    headline: {
        type: String,
        required: true,
        unique: false
    }
---and so on---
}

Additional code is included below which may or may not be relevant, but I believe this is predominantly a Mongoose issue. Any insights?

Thanks in advance Stef

Relevant markup: (in "news.html")

<div ng-controller="ArticleController">
<div><a ui-sref="app.newsdetail({id: article.id})">See details</a></div>
</div>

Markup : (in "newsdetail.html")

<div ng-controller="ArticleDetailController">
{{article.headline}}
{{article.text}}
</div>

Controllers:

.controller('ArticleController', ['$scope', '$stateParams', 'articleFactory', function ($scope, $stateParams, articleFactory) {
'use strict';
  articleFactory.getArticles().query(
      function(response) {
          $scope.articles = response;
      },
      function(response) {
          $scope.message = "Error: "+response.status + " " + response.statusText;
      }
  );
}])

.controller('ArticleDetailController', ['$scope', '$stateParams', 'articleFactory', function ($scope, $stateParams, articleFactory) {
    $scope.article = {};

    $scope.article = articleFactory.getArticles().get({id:parseInt($stateParams.id,10)})
        .$promise.then(
            function(response){
                $scope.article = response;
                $scope.showArticle = true;
            },
            function(response) {
                $scope.message = "Error: "+response.status + " " + response.statusText;
            }
    );        
}])

Service:

.service('articleFactory', ['$resource', 'baseURL',      function($resource,baseURL) {
'use strict';
    this.getArticles = function(){ 
        return $resource(baseURL+"articles/:id",null,{'get':{method:'GET' }}); 
    }; 
}]) 

Answer №1

When creating your schema, it's important to note that the _id field is already reserved and automatically indexed as type ObjectId. If you mistakenly define it as a String, it could cause issues. It's best to remove the _id field from your schema altogether. For more information, refer to the Mongoose schema documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bypassing the "Your connection is not private" error in NodeJS + Express with fetch() using Javascript

Presently, I have a setup with a NodeJS + ExpressJS client-side server that communicates with the back-end server via API calls. However, every time I make a call, I need to manually navigate to the URL of the API back-end server and click on Advanced -> P ...

AngularYelp: Node Integration for Enhanced Functionality

Embarking on a new learning journey here, so please bear with me... Discovered node-yelp while browsing Yelp's API docs. Check it out here. // Request API access: http://www.yelp.com/developers/getting_started/api_access var Yelp = require('yel ...

Unable to locate $element post minification

I've encountered a peculiar bug that only seems to manifest when my web application is running in Karaf, but not on the webpack-dev-server. Whenever I open a dialog while the web app is running in Karaf, I receive this error in the browser console: a ...

Adjusting the dimensions of the central container

Does anyone have suggestions on how to resize the middle red container when the window is resized, considering the fixed-width black containers on the left and right? I am aware that this can be achieved using jQuery by calculating the window width and a ...

How can you create a MongoDB query to retrieve the highest-selling products ranked for each individual product?

I am currently working with js and mongoose, and I am facing a challenge in solving an issue related to my orders schema in MongoDB. My goal is to retrieve the top-selling products ranked from highest to lowest. Here is an example of how a document looks l ...

Using spaces in JSON key names can create potential compatibility issues

I have a JSON structure that needs to be displayed in a table with specific keys and values. The key names contain spaces, such as "PAY ALL", "PAY PART", "DECLINE", and I need to show the corresponding values for each in the table rows. How can I achieve t ...

Convert the XML response from an API into JSON

Is there a way to convert my XML response into JSON using Angular? This is the response I am working with: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/"><?xml version="1.0" encoding="utf-8"?&gt; &lt;Fer ...

Exploring the possibilities of comprehensive root level routing in Express.js: factors to consider and strategically planning for future route expansion

I'm currently working on a Node web app using Express.js (3.0), and I want to ensure that my URLs are clean and user-friendly. Specifically, I'd like the user profiles to be accessed through domain.com/username, and for each user-created page to ...

Implementing dropdown filtering for nested ng-repeats in Angular application

I currently have the following data structure set up: vm.years = [{ year: number, proevents: [{year: number, division: string, level: string, place: string, names: string}], nonproevents: [{year: number, division: string, level: string, place: st ...

Is there any difference in loading speed when using an async function in the createConnection method of promise-mysql?

Is it more efficient to use asynchronous createConnection or not? Does this impact the loading speed in any way? I am working with express, ReactJS, and promise-mysql. Which approach is preferable? Option 1: async connect () { try{ ...

Express app: the ideal location to implement a closed-loop temperature control system

I am relatively new to working with express.js, having only created some basic client/server apps in the past. Currently, I am looking to develop a temperature controller using a PID component. However, I am struggling to grasp the architecture of express ...

Encountered an issue with Angular and RequireJS: The controller argument is not recognized as a function,

Currently, I am in the process of integrating angular with requirejs. Below is a snippet from my index.html file: <!DOCTYPE html> <html> <head> <script data-main="/js/app.js" src="/bower_components/requirejs/require.js"> ...

Tips for implementing jQuery .stop() in animations toggling

Just finished a demo of my project. I recommend checking out the JSFiddle to see exactly what's happening. I've also included the code below. HTML: <div ng-app="slideApp" ng-controller="slideCtrl"> <input type="button" value="Slid ...

Js: Automatically populating data into various input fields

I've encountered an issue with form input value injection using a <script> and POST requests. When I attempt to create another form with the same input field (same name and id), the value injection doesn't work, and troubleshooting has bee ...

What is the reason behind Express not including a body parser in its bundle?

While I grasp the inner workings of body-parser, I find it baffling that such a basic functionality is not included by default in Express. It seems rather unnecessary, considering how fundamental this feature is. Why does Express require body-parser to r ...

The Restify and HTTPS modules are causing an issue where headers cannot be set after they have already been sent to

Currently, I am attempting to integrate a call to the Google API within a restify call. However, I have encountered two issues: 1 - The error "Cannot set headers after they are sent to the client" Even after researching potential solutions for this error ...

Is it feasible to verify the request body in Node.js and Express without relying on a library?

After receiving feedback from a developer about the need to validate my request, I have consulted the code provided below: router.post('/dashboard', passport.authenticate('jwt', { session: false }), (req, res) => { try { ...

What is the best way to exclude certain values from Objects in Javascript?

Imagine having an object structured like this: "errors": { "name": { "name": "ValidatorError", "message": "Minimum length 6 characters.", "propert ...

What is the correct method for orchestrating API requests during deployment with create-react-app and an ExpressJS backend?

I have encountered a problem while trying to deploy my react application to the server. After deployment, when the app attempts to make API calls to the same server, an error occurs: Cross-Origin Request Blocked: The Same Origin Policy disallows reading ...

Serve static assets

Whenever I go to 'http://localhost:8787/article_detail/41', the css and js files are not loading. However, when I visit 'http://localhost:8787/about', all files load correctly. Why is that? app.js app.use(bodyParser.json()); app.use(b ...