如何正确使用 mongoose 的 `updateone()` 执行异步更新操作
在使用 Mongoose 进行数据库更新时,一个常见却容易被忽视的问题是:**未正确处理异步执行顺序**。如示例代码所示,`Fruit.updateOne()` 和 `Fruit.find()` 均为 Promise 返回的异步操作,若直接调用而不显式 `await`,Node.js 会立即继续执行后续代码(如 `getAllFruits()`),此时更新可能尚未提交到数据库,导致查询结果中仍显示旧值。根本原因在于 JavaScript 的事件循环机制:未 await 的 Promise 会被放入微任务队列异步执行,而同步代码(包括后续函数调用)会优先执行。因此,必须确保更新操作完成后再执行查询。
✅ 正确做法是将相关逻辑封装在 async 函数中,并对所有异步操作显式 await:
const mongoose = require('mongoose');
mongoose.connect("mongodb://127.0.0.1:27017/fruitsDB");
const fruitSchema = new
mongoose.Schema({
name: { type: String, required: [true, "No name is specified!"] },
rating: { type: Number, min: 1, max: 5 },
review: { type: String, required: true }
});
const Fruit = mongoose.model('Fruit', fruitSchema);
const getAllFruits = async () => {
const fruits = await Fruit.find({});
console.log('Current fruits:', fruits);
await mongoose.connection.close(); // 推荐 await 关闭连接
};
const runUpdateAndFetch = async () => {
try {
// ✅ 正确:等待更新完成
const result = await Fruit.updateOne(
{ _id: "64b82bbf195deb973202b544" },
{ name: "Pineapple" }
);
console.log('Update result:', result); // 查看 { matchedCount, modifiedCount, ... }
// ✅ 正确:更新后才查询
await getAllFruits();
} catch (error) {
console.error('Update failed:', error);
}
};
runUpdateAndFetch();? 关键注意事项:
掌握异步控制流是使用 Mongoose 的基础——只有确保操作时序正确,才能让更新真正生效。