在Node.js中循环填充MongoDB

时间:2018-07-12 19:45:30

标签: node.js mongodb mongoose async.js

我想使用Node.js(猫鼬)填充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!');
    });
});

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

   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);
  });
},