2016-09-26 21 views
1

我真的很感謝下面提到的一些幫助。問題是我想增加keys,比如「鷹」,「熊」等等。我的數據模型是這樣的:使用貓鼬增加子文檔密鑰

{ 
"_id" : ObjectId("57e134097a578b11eruogf0a2cb"), 
"email" : "[email protected]", 
"password" : "$2a$10$KU8vmE./gewfuh3445ryh7hDC426k0Ttd2", 
"userName" : "person", 
"votedFor" : [], 
"polls" : [ 
    { 
     "items" : { 
      "eagle" : 3, 
      "bear" : 5, 
      "lion" : 3, 
      "giraffe" : 0, 
      "elephant" : 0, 
      "monkey" : 0, 
      "gorilla" : 0, 
      "dog" : 0, 
      "cat" : 0 
     }, 
     "_id" : ObjectId("57e39435erthytvf4c16149b3fcd"), 
     "pollTitle" : "if you could be any animal, which one would you be?" 
    } 
] 
} 

這裏是我沒有成功的企圖:

User.update({"polls._id":ObjectId("57e39435erthytvf4c16149b3fcd"), 
"polls.items.bear":{$exists:true}}, {$inc:{"polls.$.items.bear":1}}) 

上面實際上robomongo工作,但奇怪的沒有我的應用程序中。它實際上創建了一個新的密鑰:"__v" :

的最新嘗試看起來像這裏面更多的是一種絕望的企圖抓住在整個文檔和繁瑣的操作方式是:

var pollItem = "bear", mongoose = require('mongoose'), 
pollID = "57e39435erthytvf4c16149b3fcd", 
id = mongoose.Types.ObjectId(pollID); 

User.findOne({"polls._id" :id},function(err,user){ 
      if(err){ 
       return err; 
      } 


      user.polls.forEach(function(poll){ 


       if(poll._id.valueOf() == pollID){ 

       var value = poll.items[pollItem]; 
        poll.items[pollItem] = value + 1; 
        return poll; 
       } 
       return poll; 
      }) 

      user.save(function(err){ 
       if(err){ 

       return (err); 
       } 
       console.log('successfully saved'); 
      }) 

      }); 

不幸的是,它似乎並沒有保存更改該文件。如果有人能指出我的方向正確,我將非常感激。

+0

在Mongoose中,當然不需要將字符串轉換爲ObjectId類型以便在查詢中使用,因爲這是在您的引擎下完成的,只要它是有效的十六進制字符串即可。 – chridam

+0

啊,好的。謝謝你讓我知道。 – Rusticman

回答

0

我想通了,看來你需要引用query對象中的document的每個級別,以便更新update對象中的正確字段。我試圖找到這個文件,但我不能,所以這是一個假設,除非有一些聰明的SO用戶可以證實這是理由。這是我做的:

User.update({"_id":ObjectId("57e134097a578b11f060a2cb"), 
"polls._id":ObjectId("57e39435c4af4c16149b3fcd"), 
"polls.items.dog":{$exists:true}}, 
{$inc:{"polls.$.items.dog":1}}) 

希望這可以幫助別人。