【问题标题】:Terminal hanging while running an asynchronous JS script to populate a Mongoose DB运行异步 JS 脚本以填充 Mongoose DB 时终端挂起
【发布时间】:2021-06-27 11:09:07
【问题描述】:

我正在处理一个个人项目,并试图了解在调用 populateTransactions() 后阻止我的 Node JS 进程终止的进程逻辑。

我认为这是因为我需要关闭数据库(我不完全清楚为什么),但是当我这样做时,进程终止但模型的 save() 函数没有完成并且数据库没有t写对了。

当我让脚本挂起时,它最终会正确填充数据库,但不会终止。


console.log("This script populates the Transaction collection so that we have some sample data for Issue #31: Uninspected Transactions Component");

let Transaction = require('./models/transaction');
let User = require('./models/user');
let mongoose = require('mongoose');

// let mongoDB = 'mongodb+srv://<username>:<password>@cluster0.dsqmg.mongodb.net/<collection-name>?retryWrites=true&w=majority';
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

async function createTransaction(inspected, recurring, amount, note, startDateString, postDateString) {

  let userQuery = await User.find({});
  userQuery = userQuery[0];

  let startDate = new Date(startDateString);
  let postDate = new Date(postDateString);

  let transaction = new Transaction({
      user: userQuery._id,
      inspected: inspected,
      recurring: recurring,
      amount: amount,
      note: note,
      startDate: startDate,
      postDate: postDate
  });

  await transaction.save((err) => {
    
    if(err){
          console.log(err);
      }
  });
  
};

async function populateTransactions(){
    await createTransaction(count,false, false, 563, "Numero Uno", "2012-12-05", "2012-12-06"); 
};

populateTransactions();

【问题讨论】:

    标签: javascript node.js mongodb mongoose async-await


    【解决方案1】:

    是的,你必须关闭连接,因为当仍然有东西在监听(数据库连接)时,nodejs 进程将无法完成。

    数据不会保存到数据库中,我猜你在save 操作完成之前关闭了数据库连接(你在这里使用回调样式???await 关键字只影响Thenable 对象,例如承诺)。

    ...
    await transaction.save(); // don't put callback as a parameter, save will return a Promise
    await db.close(); // close connection
    

    【讨论】:

    • 嘿 hoangdv,我尝试使用您建议的相同等待模式关闭我的数据库。但是,最终发生的是数据库关闭并出现错误“MongoError:拓扑已关闭,请连接”并且数据没有保存到数据库中。
    • @HunterWang 等到saving 任务完成然后关闭数据库。
    【解决方案2】:

    所以我发现问题出在

    await transaction.save((err) => {
        
        if(err){
              console.log(err);
          }
      });
    

    不遵循等待行为。事实证明,如果您将回调作为参数传递,save() 函数不会返回承诺,因此我重构了代码,使其不使用回调并且正常工作。

    【讨论】:

      猜你喜欢
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 2018-12-13
      • 2011-09-23
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多