Mongoose findById CastError:对于路径" _id"的值,转换为ObjectId失败

时间:2015-05-06 05:01:29

标签: mongodb mongoose

我有简单的应用程序,我使用mongoose在mongodb上保存数据

我也使用autoIncrement来创建mongodb自动增量ID。这是我的代码:

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);
     });

现在当我想通过_id进行查询时:

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

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

我收到此错误:

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)

查询其他字段的工作正常,我的问题只是_id字段。

1 个答案:

答案 0 :(得分:1)

似乎没有singer_id的{​​{1}}数据,您可以尝试在数据库中存在一些数据。怎么样?

"608"

当我使用错误的_id查询时遇到了同样的问题。

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

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

希望这会对你有所帮助。