I am trying to merge arrays from a request to already existing arrays in a MongoDB database. When I printed the output of the request, the arrays did not merge. What seems to be the issue here?
router.post('/add-publication-data', async (req, res) => { try { const publication = await Publications.findOne({ _id: req.body._id }); publication.toObject(); publication.additionalauthors.concat(req.body.additionalauthors) publication.students.concat(req.body.students) console.log(publication.students) publication.institutions.concat(req.body.institutions) publication.keywords.concat(req.body.keywords) publication.highlights.concat(req.body.highlights) publication.save() .then( data => { res.json(data); }) .catch(e => { res.json({ message: e }); }); } catch (err) { console.log(err); res.json({ message: err }) }; });
Advertisement
Answer
concat() method
Your result is the expected behavior of concat
method. From MDN documentation:
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
You will need to assign the result back to have the merged array, change from:
publication.additionalauthors.concat(req.body.additionalauthors)
to:
publication.additionalauthors = publication.additionalauthors.concat(req.body.additionalauthors)
push() method
Another solution is to use push
method
The push() method adds one or more elements to the end of an array and returns the new length of the array.
publication.additionalauthors.push(...req.body.additionalauthors)