gpt4 book ai didi

javascript - 使用 Mongoose 增加子文档键

转载 作者:行者123 更新时间:2023-11-28 05:30:59 25 4
gpt4 key购买 nike

我非常感谢有关以下内容的一些帮助。问题是我想将“鹰”、“熊”等加一。我的数据模型如下所示:

{
"_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,但奇怪的是不适用于我的应用程序。它实际上创建了一个新 key :"__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}})

希望这对某人有帮助。

关于javascript - 使用 Mongoose 增加子文档键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39700693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com