2013-11-04 32 views
2

基本上,我試圖計算集合中的文檔,並將新文檔設置爲_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將非常有用。

+0

如果你想創建一個自動遞增ID的集合,可以考慮不使用這些插件之一:http://plugins.mongoosejs.com/?q=increment – WiredPrairie

+0

你的鏈接沒有工作,但這裏有一個插件,你可能會或可能不會引用:https://npmjs.org/package/mongoose-auto-increment – EmptyArsenal

回答

2

首先,這是不推薦在MongoBD,因爲它不能很好地擴展。

但是如果你真的想這樣做,在官方的MongoDB文檔中有指令here,這是一個很好而且安全的方法。

基本上你使用一個小文檔來保存當前的序列ID,並且每次插入一個文檔時,你都會讀取並自動增加該序列。這比每次插入計算文檔效率高得多。

用你的解決方案,如果兩個進程同時運行會發生什麼?由於插入和序列生成/計數不是原子的,你可能會得到相同的ID。

編輯:

得到計數從模型中使用下列內容:由OP

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

編輯:

每下面的意見,問題是用異步功能同步。當所有的代碼被移動到回調函數時,它就起作用了。這裏的解決方案:

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); 
    } 
}); 
+0

感謝您的迴應。縮放並不是一個問題,因爲我只是使用Mongo來存儲我的博客文章,所以我只能一次從一臺機器插入,並且可能從多臺機器讀取。您發給我的鏈接絕對有幫助,但我試圖弄清楚如何在Mongoose中實現這一功能。我會看到適應它,但我可能會遇到同樣的問題。 – EmptyArsenal

+0

拉出的關鍵部分是使用小文檔來存儲序列。從Mongoose開始,你將執行一個'findAndModify'來獲取當前序列,並通過一個*原子*來迭代它。 –

+0

查看我的更新,希望能夠解決您的計數問題 –