[英]incrementing sub-document key using mongoose
我非常感謝有關以下所述的一些幫助。 問題是我想通過一個增加諸如'eagle','bear'等keys
。 我的數據模型如下所示:
{
"_id" : ObjectId("57e134097a578b11eruogf0a2cb"),
"email" : "test3@example.com",
"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');
})
});
不幸的是,它似乎沒有保存對文檔的更改。如果有人能指出我正確的方向,我將非常感激。
我想通了,看來你需要引用的每個級別document
的query
,以便在更新正確的領域對象update
對象。 我試圖找到這方面的文檔,但我不能,所以這是一個假設,除非一些睿智的SO用戶可以證實這是原因。 這是我做的:
User.update({"_id":ObjectId("57e134097a578b11f060a2cb"),
"polls._id":ObjectId("57e39435c4af4c16149b3fcd"),
"polls.items.dog":{$exists:true}},
{$inc:{"polls.$.items.dog":1}})
希望這有助於某人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.