【发布时间】:2020-02-20 18:40:43
【问题描述】:
我正在使用 MongoDB 和 NodeJS,并尝试在每次加载网站时预加载我的 Collection customers。我正在清空它,用空文档填充它,最后用来自外部源的真实数据替换(如果有的话)其中的任何一个。
我尝试使用save(),但它给出了错误消息'ParallelSaveError' - Can't save() the same doc multiple times in parallel. Document: 3"。它不会在渲染数据之前获取数据。这会导致仪表板中的项目丢失,只显示一两个。我读了一些关于异步函数和 Promises 的东西,但我不确定如何在我的案例中应用它们。如何实现?
dbtools.js
var empty = new Customer({
_id: '',
name: 'Unused',
surname: '',
birthday: '',
deathday: '',
phx: false,
ntw: false,
gender: 'empty'
});
module.exports = {
getCustomers: async function() {
// Fill array with empty slots
slots = [empty, empty, empty];
// Clearing collection
Customer.deleteMany({}, function(err) {});
// Looping through Array, add each Document
for (i = 0; i < slots.length; i++) {
slots[i]._id = i+1;
mongoose.connection.collection('customers').insert(slots[i]);
// or
slots[i].save(function (err) { if (err) return handleError(err); });
}
// Updating with external data
..
}
}
router.js
var tools = require('./dbtools.js');
..
router.get('/', function (req, res) {
tools.getCustomers();
Customer.find({}, function (err, customers) {
if (err) return handleError(err);
res.render('dashboard', {
title: 'Overview',
customers: customers
});
});
});
..
【问题讨论】:
-
参考这个。 link
-
@MukulDev 尝试将其包装在
try/catch中,正如那边的 vkarpov15 所建议的那样,但我仍然得到 same result..
标签: javascript node.js mongodb asynchronous mongoose