【问题标题】:How to update an array element in a mongoose db如何更新猫鼬数据库中的数组元素
【发布时间】:2017-09-24 19:29:03
【问题描述】:

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

{
    "_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”数组中的哪个元素。 .

我的问题是如何更新我的 db 文档,首先通过 id 找到它,然后在 votes 数组中定位正确的元素来更改 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;

【问题讨论】:

标签: javascript arrays node.js mongodb reactjs


【解决方案1】:

您可以使用 findOne 找到您的文档,然后保存方法来更新您的赞。

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

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2018-08-11
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2015-04-29
    • 2021-11-17
    相关资源
    最近更新 更多