使用for each在数组中添加新的数据点和对象时出现问题



我在尝试向现有数组中添加新条目时遇到问题。我正在从mongoDB获取数据。如果我用相同的方法更改对象/数组中当前的值,效果很好。我看的文件看起来和我想做的一样。我想我遗漏了什么?

var managers = await User.find({
accessLevel: [1, 2]
});
managers.forEach((manager) => {
manager.newValue = 1;
console.log(manager.newValue)
console.log(manager)
})

控制台输出为:

1
{
_id: ObjectId("62dc2a79c71582db37858ad4"),
cashierId: 5,
password: '#',
firstName: '5',
lastName: '5',
accessLevel: 1,
lastLogin: 2022-08-29T15:00:28.074Z,
roles: null,
nextTest: 2022-07-23T17:06:01.823Z,
totalTest: 0,
totalScore: 0,
__v: 0
}

预期输出:

1
{
_id: ObjectId("62dc2a79c71582db37858ad4"),
cashierId: 5,
password: '#',
firstName: '5',
lastName: '5',
accessLevel: 1,
lastLogin: 2022-08-29T15:00:28.074Z,
roles: null,
nextTest: 2022-07-23T17:06:01.823Z,
totalTest: 0,
totalScore: 0,
newValue: 1,
__v: 0
}

如果带有for循环的代码段。

var managers = await User.find({
accessLevel: [1, 2] });
const dataMonth = await Check.find({})
const dataRequiredMonth = []

dataMonth.forEach((test) => {
if (test.dateConducted.getMonth() === dayjs().month())
dataRequiredMonth.push(test)
})
for (let i = 0; i < managers.length; i++) {
managers[i].newValue = 1;
console.log(managers[i].newValue)
console.log(managers[i])
}

forEach(…(基本上为指定数组的每个元素执行回调,元素作为回调的参数传递。

该参数是函数的局部参数,因此对该参数所做的任何更改都不会反映在原始元素上

尝试使用简单的for(…(循环,它将解决您的问题。

forEach((不会改变调用它的数组-Mozila

有关forEach方法的更多信息

最新更新