Mongoose findById CastError: Cast to ObjectId failed for value at path “_id”

508 views
Skip to first unread message

Ali Reza

unread,
May 6, 2015, 9:49:13 AM5/6/15
to nod...@googlegroups.com

I have simple app , i am usign mongoose for saving data on mongodb

also i am usign autoIncrement for creating mongodb auto increment id. here is my code :


var mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');

        var connection = mongoose.connect('mongodb://localhost/mymusic', function(err) {
  if(err) {
      console.log('connection error', err);
  } else {
    console.log('connection successful');
    }
});
var Schema = mongoose.Schema;
autoIncrement.initialize(connection);

var singerSchema = new Schema({
          artist_name:  { type : String ,index: true, unique : true },
          artist_id:  { type : String },
          poster:  { type : String },
          created: { type: Date, default: Date.now },
          path: { type : String }
        });
singerSchema.plugin(autoIncrement.plugin, 'singer');
        var singer = mongoose.model('singer', singerSchema);

     var akon = new singer({
      artist_name:'Akon',
      artist_id:150,
      poster:'akon.jpg',
      path: 'akon'
     });
     // Save Singers
     akon.save(function(err){
        if(err)
        console.log(err);
        else
        console.log(fed);
     });


now when i want query by _id :

   
singer.find({ _id: 608 }, function(err, singer) {   
  if (err) throw err;

      // show the one user
      console.log(singer);
    });


i get this error :



CastError: Cast to ObjectId failed for value "608" at path "_id"   
at ObjectId.cast (/home/app/node_modules/mongoose/lib/schema/objectid.js:132:13)
    at ObjectId.castForQuery (/home/app/node_modules/mongoose/lib/schema/objectid.js:182:17)
    at module.exports (/home/app/node_modules/mongoose/lib/cast.js:202:32)
    at Query.cast (/home/app/node_modules/mongoose/lib/query.js:2334:10)
    at Query.find (/home/app/node_modules/mongoose/lib/query.js:995:10)
    at Function.find (/home/app/node_modules/mongoose/lib/model.js:1023:13)
    at Object.<anonymous> (/home/app/search.js:22:8)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)


Query for other fields works just fine , my problem its just with _id field.

Reply all
Reply to author
Forward
0 new messages