如何更新mongoose数据库中的数组元素

我正在尝试更新我的mongoose数据库中的数组的“喜欢”

{ "_id" : ObjectId("59c7eb0c4a992f8702d847a4"), "title" : "Favorite Rapper", "token" : "9b3fd295a1", "votes" : [ { "like" : 0, "vote" : "Kendric" }, { "like" : 0, "vote" : "Jcole" }, { "like" : 0, "vote" : "Kid Cudi" }, { "like" : 0, "vote" : "Kanye" }, { "like" : 0, "vote" : "A$AP Rocky" } ], "__v" : 0 } 

我想通过IDfindmongoose数据库,并更新像“票”数组中的哪个元素。 。

我的问题是我如何更新我的数据库文件,首先find它的id,然后针对投票数组中的正确的元素来改变类似的属性?

 let express = require('express'), router = express.Router(), request = require('request'), rtg = require('random-token-generator'), db = require('./db'); router.post('/', (req, res) => { let token = ''; rtg.generateKey({ len: 10, // Generate 16 characters or bytes of data string: true, // Output keys as a hex string strong: false, // Use the crypographically secure randomBytes function retry: true // Retry once on error }, function(err, key) { let newVote = { title: req.body.title, votes: req.body.categories, token: key }; //end of newVote db(newVote).save(); res.status(200).send(key); }); }); //end of post router.get('/:search', (req, res) => { let search = req.params.search console.log('votes url hit', search); db.find({ 'token': new RegExp(search, 'i') }, function(err, vote) { if (err) { console.log('err', err); res.send(500); } else { console.log('search was succesful', vote); res.status(200).send(vote); } }); }); //end of get router.put('/', (req, res) => { console.log('THIS IS WHERE I WANT TO UPDATE THE DB', req.body); res.send(200); }); //end of get module.exports = router; 

您可以使用findOnefind你的文档,然后保存方法来更新你喜欢的。

 db.findOne(findQuery, function(err, doc){ if(err) throw err; doc.votes = doc.votes ? doc.votes : []; doc.votes.forEach( (data, index, arr){ if(data.vote == "My Vote"){ arr[index]["like"] += 1 // or you new value; } }); doc.save(); })