【发布时间】:2015-07-16 01:38:23
【问题描述】:
我有一个简单的应用程序,我正在使用 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 字段。
【问题讨论】:
-
问题是 autoIncrement 插件,我不知道为什么,但是使用常规的 mongodb _id 可以正常工作。