【发布时间】:2013-11-04 12:40:11
【问题描述】:
基本上,我正在尝试计算集合中的文档,并将新文档设置为_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
});
返回相同的错误。但是,当我单独添加以下内容时,它会记录集合的长度:
PostModel.find( function( err, posts ) {
if ( !err ) {
return console.log(posts.length);
}
else {
return console.log( err );
}
});
我也尝试过以各种方式使用count(),但没有取得任何进展。有关如何查询集合以获取计数并将其设置为 _id 的任何见解都会很有帮助。
【问题讨论】:
-
如果您尝试为集合创建自动递增 id,请考虑使用以下插件之一:plugins.mongoosejs.com/?q=increment
-
您的链接无效,但这里有一个您可能会或可能不会引用的插件:npmjs.org/package/mongoose-auto-increment