如何在forEach执行后关闭mongoose连接?

时间:2016-08-01 12:50:59

标签: node.js mongodb mongoose

我有以下代码,我打开一个新的mongoose连接来插入记录,但是当我尝试在forEach(它应该是阻塞)之后关闭连接时,它会执行mongoose.connection.close()inmediatly并且不会在数据库中插入任何记录。有关如何做到这一点的任何想法?

这是我的代码

'use strict';
const mongoose = require('mongoose');
const xlsx = require('node-xlsx');
const Model = require('./model');

mongoose.connect('mongodb://localhost:27017/exel', (err) => {
   if (err) throw err;
});

let obj = xlsx.parse(file);
obj[0].data.forEach((item, index) => {
    let newItem = {
        nombre: item[2],
        localidad: item[7],
        cargo: item[8]
    }

    Model.create(newItem)
    .then((createdItem) => {
        console.log(createdItem);
    })
    .catch((err) => {
        console.log(err);
    });
});

mongoose.connection.close();

我尝试使用其中的forEach代码创建一个函数,并使用promises,使用asise和其他一些代码添加mongoose.connection.close()作为回调,但没有任何作用。

1 个答案:

答案 0 :(得分:2)

您可以使用async

例如:

async = require("async");
async.each(items, function(item, callback){
    // Call an asynchronous function, often a save() to DB
    item.someAsyncCall(function (){
      // Async call is done, alert via callback
      callback();
    });
  },
  // 3rd param is the function to call when everything's done
  function(err){
    // All tasks are done now
    doSomethingOnceAllAreDone();
  }
);
相关问题