![](/img/trans.png)
[英]Should I close MongoDB connection after that lambda function executes the code
[英]How to close mongoose connection after forEach executes?
我有以下代码在其中打开新的mongoose连接以插入记录,但是当我尝试在forEach(应该是阻塞的)之后关闭连接时,它将立即执行mongoose.connection.close()并且不会执行t在数据库上插入任何记录。 有关如何执行此操作的任何想法?
这是我的代码
'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()作为回调,使用promise,使用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();
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.