[英]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.