1
私は本当に以下の点について助言をいただきたいと思います。問題は「イーグル」「クマ」などkeys
を1つ増やしたいということです。私のデータモデルは次のようになります。mongooseを使用してサブ文書のキーを増やす
User.update({"polls._id":ObjectId("57e39435erthytvf4c16149b3fcd"),
"polls.items.bear":{$exists:true}}, {$inc:{"polls.$.items.bear":1}})
上記実際robomongoで動作しますが、妙に私のアプリの中にいません。ここで
{
"_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?"
}
]
}
は、私は成功せずに作った試みです。実際には新しい鍵:"__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');
})
});
残念ながら、それはへの変更を保存していないように誰かが正しい方向に向けることができれば、私は最も感謝しています。
Mongooseでは、文字列をObjectId型に変換する必要はありません。これは、あなたのために、また有効な16進文字列である限り、クエリで使用するためです。 – chridam
ああ、ok。知らせてくれてありがとうございます。 – Rusticman