猫鼬-在对象数组内增加一个值 [英] Mongoose - Increment a value inside an array of objects

查看:94
本文介绍了猫鼬-在对象数组内增加一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚如何增加数组内对象的值

I am having hard time figuring out how to increment a value in an object within an array

例如,我有基于Poll架构的这份文件:

For instance I have this document based on Poll schema:

{
  "_id": "584b2cc6817758118e9557d8",
  "title": "Number of Skittles",
  "description": "Test1",
  "date": "Dec 9, 2016",
  "__v": 0,
  "labelOptions": [
    {
      "Bob": 112
    },
    {
      "Billy": 32
    },
    {
      "Joe": 45
    }
  ]
}

使用快递,我可以做到这一点:

Using express, I am able to get this far:

app.put('/polls/:id', function(req, res){
  let id = req.params.id;
  let labelOption = req.query.labelOption;
  Poll.findOneAndUpdate(
    {'_id' :  id},
    {$inc: {`labelOptions.$.${labelOption}`: 1 }},
    function(err){
      console.log(err)
    })

其中labelOption是我要增加其值的那个

where labelOption is the one that I would like to increment its value

简而言之,我在文档内部进行翻译时遇到了麻烦.

To be more concise, I am having trouble transversing inside the document.

推荐答案

如果labelOptions是对象数组,则无法直接增加.find查询中的值.为了简化操作,您应该将labelOptions类型从对象数组"更改为对象":

It is not possible to directly increment the value in the .find query if labelOptions is an Array of Object. To make it easier, you should change the labelOptions type from Array of Objects to Object:

"labelOptions": {
    "Bob": 112,
    "Billy": 32,
    "Joe": 45
};

如果要通过文档的_id查询,也可以考虑使用.findByIdAndUpdate而不是.findOneAndUpdate.然后,您可以通过以下方式实现所需的目标:

Also consider using .findByIdAndUpdate instead of .findOneAndUpdate if you are querying by the document's _id. And then, you can achieve what you want by:

Poll.findByIdAndUpdate(
    id,
    {$inc: {`labelOptions.${labelOption}`: 1 }},
    function(err, document) {
    console.log(err);
});

更新:如果您坚持将对象数组用于labelOptions,则有一种解决方法:

UPDATE: If you are persistent on using Array of Objects for labelOptions, there is a workaround:

Poll.findById(
    id,
    function (err, _poll) {

        /** Temporarily store labelOptions in a new variable because we cannot directly modify the document */
        let _updatedLabelOptions = _poll.labelOptions;

        /** We need to iterate over the labelOptions array to check where Bob is */
        _updatedLabelOptions.forEach(function (_label) {

            /** Iterate over key,value of the current object */
           for (let _name in _label) {

               /** Make sure that the object really has a property _name */
               if (_label.hasOwnProperty(_name)) {

                   /** If name matches the person we want to increment, update it's value */
                   if (_name === labelOption) ++_label._name;
               }
           }
        });

        /** Update the documents labelOptions property with the temporary one we've created */
        _poll.update({labelOptions: _updatedLabelOptions}, function (err) {

            console.log(err);
        });
    });

这篇关于猫鼬-在对象数组内增加一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆