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');
})
});
不幸的是,它似乎并没有保存更改该文件。如果有人能指出我的方向正确,我将非常感激。
在Mongoose中,当然不需要将字符串转换为ObjectId类型以便在查询中使用,因为这是在您的引擎下完成的,只要它是有效的十六进制字符串即可。 – chridam
啊,好的。谢谢你让我知道。 – Rusticman