2016-08-01 1 views
0

레코드를 삽입하기 위해 새로운 몽구스 연결을 여는 다음 코드를 가지고 있지만 forEach (차단 예정) 이후에 연결을 닫으려고하면 mongoose.connection.close()가 inmediatly와 데이터베이스에 레코드를 삽입하지 않습니다. 이 작업을 수행하는 방법에 대한 아이디어가 있습니까? 여기 forEach가 실행 된 후 몽구스 연결을 닫는 방법?

내 코드

'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 코드 함수를 작성하고 콜백으로 mongoose.connection.close()를 추가하는 시도와 몇 가지 다른지만 아무것도 작동하지 않습니다.

+2

. 'forEach'는 블로킹 상태입니다.하지만 모든 상황을 반복하고'Model.create'를 호출하면 즉시 반환됩니다 (콜백이 대기 중입니다). 이것은'mongoose.connection.close'가 거의 즉시 실행된다는 것을 의미합니다. 각 루프마다 비동기식으로 비동기식을 살펴보십시오. – MrWillihog

답변

1

이 경우 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(); 
    } 
); 
관련 문제