【问题标题】:Fetching data, edit MongoDB Collection before loading webapp? Async, Promises?在加载 webapp 之前获取数据、编辑 MongoDB 集合?异步,承诺?
【发布时间】: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


【解决方案1】:

根据 getCustomers 函数中的async,函数中存在 Promises/async 调用。如果是这样,任何调用该函数的函数都需要在前面加上 await 才能捕获异步回调。

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

如果有帮助请告诉我

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 2019-04-13
    • 1970-01-01
    • 2015-03-17
    • 2018-07-19
    • 1970-01-01
    • 2020-03-31
    • 2018-07-20
    相关资源
    最近更新 更多