如何更新mongoose db中的数组元素

时间:2017-09-24 19:29:04

标签: javascript arrays node.js mongodb reactjs

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

{
    "_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
}

我想通过id找到mongoose db并更新“votes”数组中哪个元素的类似内容。

我的问题是如何更新我的数据库文档,首先通过id找到它然后定位投票数组中的右元素来更改like属性?

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;

1 个答案:

答案 0 :(得分:1)

您可以使用findOne找到doc然后保存方法来更新您的喜欢。

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();
})