mongo.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // const { MongoClient } = require('mongodb');
  2. var us = {
  3. mongo: require('mongodb'),
  4. client: null // 用于存储 MongoClient 实例
  5. };
  6. // 初始化 MongoDB 连接
  7. us.initMongoConnection = async function (host, database) {
  8. if (!us.client) {
  9. const url = host; // MongoDB 连接地址
  10. us.client = new us.mongo.MongoClient(url, {
  11. useNewUrlParser: true,
  12. useUnifiedTopology: true,
  13. maxPoolSize: 10000, // 设置连接池没有上限
  14. serverSelectionTimeoutMS: 5000, // 服务器选择超时
  15. socketTimeoutMS: 45000 // 套接字超时
  16. });
  17. try {
  18. await us.client.connect();
  19. } catch (err) {
  20. console.error("MongoDB 连接失败", err);
  21. throw err; // 抛出错误以便调用者处理
  22. }
  23. }
  24. return us.client.db(database); // 返回数据库实例
  25. }
  26. async function updateUserData(host, database, cename, data) {
  27. const db = await us.initMongoConnection(host, database); // 连接数据库
  28. try {
  29. const collection = db.collection(cename); // collection设置
  30. const dateKey = Object.keys(data)[0]; // 获取日期键
  31. const username = Object.keys(data[dateKey])[0]; // 获取用户ID
  32. console.log(`更新用户数据:${username}`);
  33. // 使用 upsert 更新或插入文档
  34. await collection.updateOne(
  35. { [dateKey]: { $exists: true }, [`${dateKey}.${username}`]: { $exists: true } }, // 查询条件
  36. {
  37. $push: { [`${dateKey}.${username}`]: data[dateKey][username] }, // 将用户数据推入数组
  38. },
  39. { upsert: true } // 如果没有数据,默认创建一条数据
  40. );
  41. console.log('数据更新成功');
  42. } catch (err) {
  43. console.error('更新失败', err);
  44. }
  45. }
  46. /*
  47. // 示例调用
  48. updateUserData("mongodb://root:usestudio-1@123.58.32.151:11641?authSource=admin", "cocolog", "applog", {
  49. "2025-03-24": {
  50. "username":
  51. {
  52. userid: "",
  53. data: "",
  54. appname: "",
  55. status: ""
  56. }
  57. }
  58. });
  59. */