Aneta Jabłońska
Aneta Jabłońska

Reputation: 125

updating the nested arrays in mongodb and nodejs

I can't update array cards by api. I have doc board :

        {
"_id" : ObjectId("59e096a7622a3825ac24f343"),
"name" : "1",
"users" : [ 
    ObjectId("59cd114cea98d9326ca1c421")
],
"lists" : [ 
    {
        "list" : "1",
        "cards" : [ 
            {
                "name" : "2",
                "Author" : [ 
                    "59df60fb6fad6224f4f9f22d", 
                    "59df60fb6fad6224f4f9f22d", 
                    "59df60fb6fad6224f4f9f22e"
                ]
            }, 
            {
                "name" : "3",
                "Author" : []
            }
        ]
    }, 
    {
        "list" : "fea",
        "cards" : [ 
            {
                "name" : "card",
                "Author" : []
            }
        ]
    }
],
"__v" : 0 }

I create function which is sended variable object with:

cardsObj = {
  indeksCard : indeksCard,
  cards : cards,
  IdBoard: IdBoard
}

IdBoard is ID which Board i want update, cards it is array which I want only update, and indeksCard is numer position cards array in lists.

so cardsObj.cards it seems :

        {
            "name" : "3",
            "Author" : ["59df60fb6fad6224f4f9f22d"]
        }

Ok I send to API where I get in function :

router.post('/add/author', function (req, res, next) {
var query = 'lists.'+req.body.cardsObj.indeksCard+'.cards';

  Board.findOneAndUpdate({ _id: req.body.cardsObj.IdBoard },
    {
      $set: {
         query: req.body.cardsObj.cards,
      }
    },
    {
      upsert: true
    },
    ((cards) => {
      res.send(cards)
    })
  )
});

Please to someone helped me, it is very important for me. And problem is that this function Board.findOneAndUpdate does not update my array i think its fault query.

Upvotes: 0

Views: 24

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

Mongodb is taking your variable query as a property('query' as another field) in the Board collection schema. It is not able to evaluate the query variable to give you the array property that you want.

To allow MongoDB to evaluate the variable, you can use [] around your query variable. this is known as ComputedPropertyName, defined in ES6.

Try this :

Board.findOneAndUpdate({ _id: req.body.cardsObj.IdBoard },
    {
      $set: {
         [query]: req.body.cardsObj.cards,
      }
    },
    {
      upsert: true
    },
    ((cards) => {
      res.send(cards)
    })
  )
});

Look here for detailed information on ComputedPropertyName.

Upvotes: 0

Related Questions