如何实现MongoDB同步查询?确保后续代码在数据检索完成后执行
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:
awaitonly works insideasyncfunctions, so you need to wrap your logic accordingly.- Adding
try/catchensures you catch any errors from the database queries (like connection issues or invalid data). - I also added
awaitto theinsertcalls—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
insertcalls 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

