データベース内のドキュメントを数え、その数を使用して_idを作成することにより、Mongooseモデルの_idを動的に作成しようとしています(最初の_idが0であると仮定します)。ただし、値から _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' }
何が起こっているか知っているなら、私に知らせてください。