¿为什么我不能在此查询处理程序中连接两个数组?

¿Why can't I concatenate two arrays in this query handler?

我正在尝试将请求中的数组合并到 MongoDB 数据库中的现有数组。当我打印请求的输出时,数组没有合并。这似乎是什么问题?

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

concat() 方法

您的结果是 concat 方法的预期行为。来自 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.

您需要将结果分配回合并数组,更改自:

publication.additionalauthors.concat(req.body.additionalauthors)

至:

publication.additionalauthors = publication.additionalauthors.concat(req.body.additionalauthors)

push() 方法

另一个解决方案是使用push方法

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)