I am coding a website and found this strange [Error:Invalid ObjectId] printing out in my console.log, here is situations when the error will occur:
1) When I restart node server and re logged in, at the home page, there is no such error; But once I clicked into the item page for and only for the first time, I will get a
[Error: Invalid ObjectId]
I located that this error is printed out by the "/items/:id" controller;
I refreshed the page constantly, and it never occurred again
2) Another situation for this error to occur is when I do nothing, like just now, only typing in stack-overflow, and for a certain amount of time, I will get one more such error. This error bothered me, because if I go out for 1~2 hours, my development server will have maybe 20 of such errors when I come back and it will be jammed and does not respond very quickly (takes about 2 minutes to respond)
I am using Jade, backbone.js, express.js and mongoose; But I didn't use anything like socket.io and I do believe my backbone also does not call the server for a certain amount of time. (unless my knowledge about backbone is wrong.)
Here is the codes simplified:
1) The link I clicked:
a(href!="/items/<%=_id%>") click
2) The controller generating this error:
//GET an item
app.get('/items/:id',function(req,res){
models.ItemModel.findOne({_id:req.params.id},function(err,item){
if (!err){
item.rtime=app.moment(item.ctime).fromNow();
render(req,res,'item.jade',item)
} else
console.log(err)
})
})
The render function is an encapsulated function, the index page also use that function and no error occurs, so I think it has nothing to do with render().
Currently, what I am sure is that the controller is definitely called twice when the link is clicked for the first time. The first call is normal and return the page, but the second call seems to be an empty call and returns a null item.
Does anyone have this similar situation before? Or maybe some ideas about how to solve this problem?
I had the same problem when I was browsing in Chrome. It seems in my case there was a plugin (most probably UA spoofer) that was issuing a second request. I verified that in Safari the request is called only once. Try turning off all plugins in your browser or use another browser to test.
Use {_id:req.params.id.toString()}
The ObjectID is normally an object, but Mongoose expects a String when searching. Adding toString() to ObjectIDs and to Strings makes it safe.