【问题标题】:How to close mongoose connection after forEach executes?forEach 执行后如何关闭猫鼬连接?
【发布时间】:2016-08-01 21:52:34
【问题描述】:

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

这是我的代码

'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 和其他一些方法,但没有任何效果。

【问题讨论】:

  • 您误解了节点是如何异步工作的。 forEach 正在阻塞,正如您所说,但是,您会循环遍历所有内容并调用立即返回的Model.create(它正在等待触发它的回调)。这意味着mongoose.connection.close 将几乎立即执行。尝试查看 async 以了解每个循环的异步情况。

标签: node.js mongodb mongoose


【解决方案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();
  }
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2012-02-07
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    相关资源
    最近更新 更多