Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

This Error is Occurring based on the order of the route/function defined and i have also searched different reasons for this error's occurrence but din't come across this specific reason

//Save Task

    router.get("/tasks/newrec",function(req,res,next){
        var newtask={
            title:"newtask5",
            isdone:"true"
        }

        db.tasks.save(newtask,function(error,result){
            if(error){res.send(error); }
            else
            { res.send("success"); }//res.json(result);}
        });    

    });

If i am declaring this function first then i see no error if i am declaring as second or third function then i see this error.I am using node with mongojs.

var express=require('express');
var router=express.Router();
var mongojs= require('mongojs');
var db=mongojs('taskdb',['tasks']);


//display all tasks
router.get('/tasks',function(req,res,next){

    db.tasks.find(function(err,tasks){
           res.json(tasks);
    });

});

//To find single record with id
router.get('/tasks/:id',function(req,res,next){
    var uid = req.params.id.toString();
    db.tasks.findOne({_id:mongojs.ObjectId(uid)},function(err,doc){
       res.json(doc);
    });
});


//Save Task

router.get("/tasks/newrec",function(req,res,next){
    var newtask={
        title:"newtask5",
        isdone:"true"
    }

    db.tasks.save(newtask,function(error,result){
        if(error){res.send(error); }
        else
        { res.send("success"); }//res.json(result);}
    });    

});
like image 760
Arun3x3 Avatar asked Dec 24 '22 10:12

Arun3x3


1 Answers

Probably related with order of paths declaration, I suffered it sometimes. These are your paths:

  • /tasks
  • /tasks/:id
  • /tasks/newrec

All 3 are GET methods. Problem comes because some request paths come match in several paths. For example, /tasks/something matchs in the second one, but in the first one. Even /tasks/newrec, you are thinking it matchs with the third, but it matches with the 3 paths. And express avaluate the paths in the order you declare them, so it won't ever get into third path. That's why I think express raise the error. The basic rule is for each HTTP method always declare more specific paths before. In your case, this would be the right order:

  • /tasks/newrec
  • /tasks/:id
  • /tasks

Just the opposite you did. Hope it helps

like image 84
David Vicente Avatar answered Feb 12 '23 09:02

David Vicente