在 Node.js 中循环填充 MongoDB

Populating MongoDB in a loop in Node.js

我想使用 Node.js (mongoose) 填充 MongoDB 数据库。在建立数据库连接后,我试图异步执行此操作(使用 async.js),但它没有像我希望的那样工作。不是用少量文档填充数据库,而是在写入之前打开和关闭数据库连接。听起来是一个很典型的异步问题,但我一头雾水

我目前的代码如下

var runStart = '2019-01-01 00:00:00';
var runEnd = '2019-01-17 00:00:00';
var periods = [];
var d = moment(runStart);
while (d < moment(runEnd)) {
  periods.push([d.format(), d.add(1, 'day').format()]);
}

mongoose.connect(config.db);
const db = mongoose.connection;
db.on('error', () => {
  throw new Error('unable to connect to database');
});
db.on('open', () => {
  console.log('DB open');
  async.each(
    periods,
    function(period, next) {
      Period({
        start: moment(period[0]),
        end: moment(period[1]),
        type: 'delivery',
        notes: ''
      }).save((err) => {
        if (err) callback(err);
      });
      next();
    },
    function(err) {
      db.close();
      console.log('FINISHED!');
    });
});

我做错了什么?

   function(period, next) {
      Period({
        start: moment(period[0]),
        end: moment(period[1]),
        type: 'delivery',
        notes: ''
      }).save((err) => {
        if (err) callback(err); // `callback` is supposed to be `next
      });
      next();  // `next` is called before the document is saved
    },

将该代码更改为:

function(period, next) {
  Period({
    start: moment(period[0]),
    end: moment(period[1]),
    type: 'delivery',
    notes: ''
  }).save((err) => {
    next(err);
  });
},