基本上,我試圖計算集合中的文檔,並將新文檔設置爲_id。我已經嘗試了一些組合,但他們都沒有工作。試圖在Mongoose中動態生成_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的集合,可以考慮不使用這些插件之一:http://plugins.mongoosejs.com/?q=increment – WiredPrairie
你的鏈接沒有工作,但這裏有一個插件,你可能會或可能不會引用:https://npmjs.org/package/mongoose-auto-increment – EmptyArsenal