获取数据,在加载webapp之前编辑MongoDB集合?异步,承诺



我使用MongoDB和NodeJS,每次加载网站时都试图预加载我的Collectioncustomers。我清空它,用空文档填充它,最后用外部来源的真实数据替换(如果可用(其中的任何一个。

我尝试使用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
});
});
});
..

基于getCustomers函数中的async,该函数中存在Promise/async调用。如果是这样的话,任何调用该函数的函数都需要在前面有一个await才能捕获异步回调。

router.get('/', function(req, res) {
try {
const customers = await tools.getCustomers();
res.render(...);
} catch (e) {
return handleError(err);
}
});

请告诉我这是否有助于

最新更新