[英]Running a forEach() on an Array of Objects After Retrieving with findOne() in Mongo Back-end
我正在使用findOne()来检索这样的文档:
let staffToUpdate = await Staff.findOne({
_id: request.parameters.id
}).exec();
let historyArray = await crewToUpdate.history;
console.log("historyArray: ", await historyArray);
console.log(Array.isArray(historyArray)); // returns true
数据如下所示:
history: [
{
status: "active",
startDate: <Date>,
endDate: <Date>,
completed: false
},
{
status: "training",
startDate: <Date>,
endDate: <Date>,
completed: true
}
]
当我执行上述操作时,我得到了打印出的对象数组,并在检查中返回“ true”以查看“ historyArray”是否确实是数组。
因此,现在有了这个数组,我想对在其中找到的对象进行转换,如下所示:
let updatedHistoryArray = historyArray.then(
updatedHistoryArray.forEach(history => {
history.completed = true;
history.endDate = new Date();
})
);
但是,这是不起作用的部分。 当我尝试这个我得到这个错误:
原因:ReferenceError:historyArray未定义
我在这里想念什么?
更新:在下面的评论者的建议之后,我尝试了此操作:
let staffToUpdate = await Staff.findOne({
_id: request.parameters.id
}).exec();
let staffObject = staffToUpdate.toObject();
let historyArray = await staffObject.history;
console.log(await historyArray); // prints the array
console.log(Array.isArray(historyArray)); // returns true
historyArray.forEach(history => { // this is where the error occurs
history.completed = true;
history.endDate = new Date();
});
在这最后的代码块中,我得到此错误:
原因:ReferenceError:historyArray未定义
historyArray
不是一个Promise,您不能在then
上运行。 该代码何时运行
let staffToUpdate = await Staff.findOne({
_id: request.parameters.id
}).exec();
它等待直到执行查询,然后分配实际结果(猫鼬Document)而不是promise ,并将其分配给staffToUpdate
。 您需要在猫鼬文档上运行toObject()
以获取没有包装器的纯对象:
const unwrappedStaffToUpdate = staffToUpdate.toObject();
之后,您无需在crewToUpdate.history
上使用await
,因为它不是Promise,而是同步的。 这就是为什么你不能运行then
在historyArray
因为它是一个正常的阵列,而不是承诺。
试试这个代码:
unwrappedStaffToUpdate.historyArray.forEach(history => {
history.completed = true;
history.endDate = new Date();
});
或者,如果您不想更改Array,请使用map
代替forEach
:
const updatedHistoryArray = unwrappedStaffToUpdate.historyArray.map(history => ({
...history
completed: true;
endDate: new Date()
})
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.