const express = require('express');
const router = express.Router();
const { MongoClient } = require('mongodb');
// 连接字符串
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
// 定义路由处理函数
router.get('/updateProducts', async (req, res) => {
try {
// 连接到MongoDB
await client.connect();
const db = client.db('yourDatabaseName'); // 替换为你的数据库名
const productsCollection = db.collection('products');
// 查询category为electronics且price大于100的产品
const query = { category: 'electronics', price: { $gt: 100 } };
// 更新操作,将price提高10%
const update = {
$mul: {
price: 1.1
}
};
const result = await productsCollection.updateMany(query, update);
res.status(200).json({
message: `成功更新 ${result.modifiedCount} 个产品`,
result: result
});
} catch (err) {
console.error(err);
res.status(500).json({ error: '服务器错误' });
} finally {
// 关闭数据库连接
await client.close();
}
});
module.exports = router;