简体   繁体   中英

How to update an array element in a mongoose db

I am trying to update the "like" of an array in my 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
}

I would like to find the mongoose db by the id and update the like of which ever element in the "votes" array. .

My question is How do i update my db document by first finding it by the id and then targeting the right element in the votes array to change the like property?

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;

You can use findOne to find you doc then save method to update your like.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM