You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现MongoDB同步查询?确保后续代码在数据检索完成后执行

How to Run Code After MongoDB Query Completes (Synchronous-Like Execution)

Hey there! The core issue here is that MongoDB operations (like find().count()) are asynchronous by default—they return a Promise instead of immediately giving you the count value. That means your original code would run the if check before the database query finishes, leading to incorrect behavior.

Let's fix this with two common, reliable approaches:

1. Use async/await (Modern, Readable Approach)

Wrap your logic in an async function and use await to pause execution until the count query completes. This makes your code look "synchronous" while still handling async operations properly:

// Declare the containing function as async
async function handleTransaction(userId, merchant_name, amt, trxn) {
  try {
    // Wait for the count query to finish and get the actual number
    const brandExists = await Brands.find({ name: trxn.name }).count();

    // This code runs ONLY after the count query completes
    if (brandExists === 0) {
      await Brands.insert({ name: trxn.name, logo: "default.png" });
      await Trxs.insert({ userId, merchant_name, amt });
    }
  } catch (err) {
    // Always handle potential database errors!
    console.error("Error processing transaction:", err);
  }
}

Key Notes:

  • await only works inside async functions, so you need to wrap your logic accordingly.
  • Adding try/catch ensures you catch any errors from the database queries (like connection issues or invalid data).
  • I also added await to the insert calls—these are also async, so waiting for them ensures you don't fire off multiple unhandled operations.

2. Use Promise .then() (Legacy/Alternative Approach)

If you're working in an environment where async/await isn't available, you can use the Promise chain with .then() to run code after the query completes:

Brands.find({ name: trxn.name }).count()
  .then(brandExists => {
    // This runs after the count query finishes
    if (brandExists === 0) {
      // You can chain these inserts too if needed
      return Brands.insert({ name: trxn.name, logo: "default.png" })
        .then(() => Trxs.insert({ userId, merchant_name, amt }));
    }
  })
  .catch(err => {
    console.error("Error checking brand or inserting data:", err);
  });

Key Notes:

  • The .then() callback receives the resolved count value as its argument.
  • Chaining the insert calls ensures the Trxs insert only runs after the Brands insert completes (optional, but useful for dependent operations).
  • Always include a .catch() to handle errors anywhere in the Promise chain.

Why Your Original Code Didn't Work

In your original snippet, const brandExists = Brands.find({name: trxn.name}).count(); assigns a Promise object to brandExists, not the actual count number. Comparing a Promise to 0 will always be false, so your if block would run incorrectly (or not run when it should) before the query finishes.

内容的提问来源于stack exchange,提问作者Justin A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:06:45