尝试在Mongoose中dynamic生成_id,但返回对象

基本上,我试图计算一个集合中的文档,并将新文档设置为_id。 我已经尝试了一些组合,但他们都没有工作。

这是我的尝试:

var count = PostModel.find( function( err, posts ) { if ( !err ) { return posts.length; } else { return console.log( err ); } }); var post = new PostModel({ _id: count, title: request.body.title, content: request.body.content, tags: request.body.tags }); 

返回:

 { message: 'Cast to number failed for value "[object Object]" at path "_id"', name: 'CastError', type: 'number', value: { options: { populate: {} }, safe: undefined, _conditions: {}, _updateArg: {}, _fields: undefined, op: 'find', model: { [Function: model] modelName: 'Post', model: [Function: model], options: undefined, db: [Object], schema: [Object], collection: [Object], base: [Object] } }, path: '_id' } 

和这个:

 var post = new PostModel({ _id: PostModel.find( function( err, posts ) { if ( !err ) { return posts.length; } else { return console.log( err ); } }), title: request.body.title, content: request.body.content, tags: request.body.tags }); 

哪个返回相同的错误。 但是,当我分别添加以下内容时,它会logging集合的长度:

 PostModel.find( function( err, posts ) { if ( !err ) { return console.log(posts.length); } else { return console.log( err ); } }); 

我也以各种方式尝试使用count() ,但是我无法取得任何进展。 任何有关如何查询计数集合的见解,并将其设置为_id将是非常有用的。

首先,MongoBD 不推荐这样做,因为它不能很好地扩展。

但是如果你真的想这样做的话,在官方的MongoDB文档中有一些指示,这是一个很好而且安全的方法。

基本上你使用一个小文件来保存当前的序列号,每次插入一个文件,你都会读取并自动增加序列号。 每次插入时,比计算文档效率更高。

用你的解决scheme,如果两个进程同时运行会发生什么? 您可能会以相同的ID结束,因为您的插入和序列生成/计数不是primefaces的。

编辑:

要从您的模型计数使用以下内容:

 PostModel.count( function (err, count) { if (err) .. console.log('there are %d posts', count); }); 

由OP编辑:

根据下面的评论,问题是同步使用asynchronousfunction。 当所有的代码被移到callback函数,它的工作。 这是解决scheme:

 PostModel.count( function (err, count) { if (err) console.log(err); else { console.log('there are %d posts', count); 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 ); } }); return response.send(post); } });