i have following code open new mongoose connection insert records, when try close connection after foreach (which supposed blocking) executes mongoose.connection.close() inmediatly , doesn't insert records on database. ideas of how this?
here code
'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();
i tried creating function foreach code inside , adding mongoose.connection.close() callback, using promises, using async , few others nothing works.
you can use async this.
for example:
async = require("async"); async.each(items, function(item, callback){ // call asynchronous function, save() db item.someasynccall(function (){ // async call done, alert via callback callback(); }); }, // 3rd param function call when everything's done function(err){ // tasks done dosomethingonceallaredone(); } );
Comments
Post a Comment