0
出於測試目的,我想控制我的MongoDb對象中的createdAt
字段。不幸的是,我擔心這不可能通過標準的timestamp執行。下面是我使用的是創建一些對象,然後設置其創建時間戳代碼的要點:用貓鼬操縱createdAt字段
const docArray = [];
const times = [15, 32, 1233, 122].map(seconds => moment().add(seconds, 'seconds'));
for (let i = 0; i < times.length; i += 1) {
// Create an object
docArray.push(await createObj(`${i}`));
const doc2update = await MyModel.findById(docArray[i]._id);
// Save the original created date
const org = doc2update.createdAt;
// Do the update
doc2update.createdAt = times[i];
doc2update.save(); // tried doc2update.update() without change
// Retrieve the updated object
docArray[i] = await TaskModel.findById(docArray[i]._id);
// Check if change preserved
console.log(docArray[i].createdAt - org,
'vs expected',
doc2update.createdAt - org);
}
輸出是相當令人失望的
0 'vs expected' 14841
0 'vs expected' 31809
0 'vs expected' 1232787
0 'vs expected' 121762
我猜法操縱創造了這種方式不建議常規使用,但測試時會很方便。有沒有解決的辦法?
您能解釋一下您正在嘗試做什麼嗎? – nadavvadan
@nadavvadan:我想計算創建的對象(實際上是子文檔)之間的中位時間,但是我想控制createdAt時間戳。我可以當然只是添加延遲的對象,但它會(1)增加不必要的測試時間(2)缺乏相同的精度,因爲我仍然無法控制精確的時間 –