2014-09-21 39 views
1

更新的開頭插入元素: 這裏的問題是,本地的MongoDB驅動程序所需要的的objectID比貓鼬不同的格式。我需要做{_id:new mongoose.Types.ObjectId(story_id)},而不是{_id:story_id}。它僅返回兩個字段的原因是它使用{_id:story_id}創建了一個新文檔,而不是更新{_id:{$ oid:story_id}}文檔。然而,我原來的原因與原生驅動程序與貓鼬做到這一點,結果不起作用。即使是本地驅動程序也不接受正的$ slice值。所以我仍然在尋找一種方法來使用Mongoose或通過Mongoose訪問的本地驅動程序(不支持$ position或$ slice正值)插入一個數組的開頭。findAndModify的MongoDB在陣列

當我運行下面的查詢,返回的結果只包含_id,消息和參與者。我希望獲得完整的故事記錄,而不僅僅是更新後的字段。有沒有辦法做到這一點?根據Node MongoDB Native驅動程序文檔(http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#findandmodify),mongo控制檯中的「fields」參數未在findAndModify驅動程序中實現。我想避免必須做第二次查詢才能獲得剛剛更新的記錄。

Story.collection.findAndModify(
{"_id": story_id}, 
{"_id": "asc"}, 
{ 
    "$push": { 
"messages": { 
    "$each": [message], 
    "$sort": { "_id": -1}, 
    "$slice": 500 
    }, 
    }, 
    "$addToSet": {"participants": user_id}, 
}, 
    {new: true}, 
    {fields: {"feeling":1, "description":1, "image_height":1, "image_width":1, "storyteller":1, "image_url":1, "participants":1}}, // -> this line is ignored by MongoDB native driver 

     {upsert: true} 

) 
+0

你是不是在調用['Story.findByIdAndUpdate'](http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate)?無論如何,你應該得到整個文檔,而不僅僅是更新的領域。 – JohnnyHK 2014-09-21 13:28:15

+0

貓鼬findByIdAndUpdate沒有支持用於添加到陣列的開始,就像我跟$排序和$片在這裏做(貓鼬看起來負$切片的值和如下所示不會返回整個返回一個錯誤。這個查詢DOC回 – 2014-09-21 22:58:27

回答

2

可以插入在陣列字段開頭的元素與使用$each$position修飾符(這是由貓鼬支持)一個$push:如果您使用貓鼬,爲什麼

Story.findByIdAndUpdate(story_id, { 
    $push: { 
     messages: { 
     $each: [message], 
     $position: 0 
     }, 
    }, 
    $addToSet: {participants: user_id}, 
    }, { 
    new: true, 
    upsert: true 
    }, 
    function (err, newDoc) { ... } 
); 
+2

貓鼬不支持通過$位置參數。見:https://github.com/LearnBoost/mongoose/issues/2024這裏最後回覆」 http://stackoverflow.com/questions/23083041/如何插入到特定位置在數組在sub -ocument-by-using-m從貓鼬錯誤是$ $每個只能與$ sort或$切片配對 – 2014-09-22 00:57:20

+0

@PraneethWanigasekera該錯誤被標記爲[3.8.12中修復](https://github.com/LearnBoost/mongoose/commit/6cddf8441dad0d6fb9c4588d4cb05b7d71d44b90),並且當我用Mongoose 3.8.16測試它時它工作正常。 – JohnnyHK 2014-09-22 01:04:02

+0

它會很棒如果它工作的話,我也使用3.8.16,這裏是錯誤我得到與上面的代碼:{[OperationalError:異常:$每個術語只需要$切片(和任選$排序)作爲補] 名:「OperationalError」, 消息:異常:$每個術語只需要$切片(和可選$排序)爲補, 原因: {[MongoError:異常:$每學期只需要$片(和可選$排序)作爲補充]非常感謝您的幫助。 – 2014-09-22 01:46:49