如何在Mongoose中设置_id到db文件?

我试图通过计算数据库中的文档,并使用该数字来创build_id(假设第一个_id为0),dynamic地为我的Mongoose模型创build_id。 但是,我无法从我的价值观中获得_id。 这是我的代码:

//Schemas var Post = new mongoose.Schema({ //_id: Number, title: String, content: String, tags: [ String ] }); var count = 16; //Models var PostModel = mongoose.model( 'Post', Post ); app.post( '/', function( request, response ) { var post = new PostModel({ _id: count, title: request.body.title, content: request.body.content, tags: request.body.tags }); post.save( function( err ) { if( !err ) { return console.log( 'Post saved'); } else { console.log( err ); } }); count++; return response.send(post); }); 

我试图设置_id许多不同的方式,但它不适合我。 这是最新的错误:

 { message: 'Cast to ObjectId failed for value "16" at path "_id"', name: 'CastError', type: 'ObjectId', value: 16, path: '_id' } 

如果你知道发生了什么,请告诉我。

您需要将_id属性声明为模式的一部分(您已将其注释掉),或者使用_id选项并将其设置为false (您正在使用id选项,该选项创build一个虚拟getter将_id转换为string但仍然创build了一个_id ObjectID属性,因此铸造错误,你会得到)。

所以要么这个:

 var Post = new mongoose.Schema({ _id: Number, title: String, content: String, tags: [ String ] }); 

或这个:

 var Post = new mongoose.Schema({ title: String, content: String, tags: [ String ] }, { _id: false }); 

第一件@ robertklep的代码不适合我(mongoose4),也需要禁用_id

 var Post = new mongoose.Schema({ _id: Number, title: String, content: String, tags: [ String ] }, { _id: false }); 

这对我有用