123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- // const { MongoClient } = require('mongodb');
- var us = {
- mongo: require('mongodb'),
- client: null // 用于存储 MongoClient 实例
- };
- // 初始化 MongoDB 连接
- us.initMongoConnection = async function (host, database) {
- if (!us.client) {
- const url = host; // MongoDB 连接地址
- us.client = new us.mongo.MongoClient(url, {
- useNewUrlParser: true,
- useUnifiedTopology: true,
- maxPoolSize: 10000, // 设置连接池没有上限
- serverSelectionTimeoutMS: 5000, // 服务器选择超时
- socketTimeoutMS: 45000 // 套接字超时
- });
- try {
- await us.client.connect();
- } catch (err) {
- console.error("MongoDB 连接失败", err);
- throw err; // 抛出错误以便调用者处理
- }
- }
- return us.client.db(database); // 返回数据库实例
- }
- async function updateUserData(host, database, cename, data) {
- const db = await us.initMongoConnection(host, database); // 连接数据库
- try {
- const collection = db.collection(cename); // collection设置
- const dateKey = Object.keys(data)[0]; // 获取日期键
- const username = Object.keys(data[dateKey])[0]; // 获取用户ID
- console.log(`更新用户数据:${username}`);
- // 使用 upsert 更新或插入文档
- await collection.updateOne(
- { [dateKey]: { $exists: true }, [`${dateKey}.${username}`]: { $exists: true } }, // 查询条件
- {
- $push: { [`${dateKey}.${username}`]: data[dateKey][username] }, // 将用户数据推入数组
- },
- { upsert: true } // 如果没有数据,默认创建一条数据
- );
- console.log('数据更新成功');
- } catch (err) {
- console.error('更新失败', err);
- }
- }
- /*
- // 示例调用
- updateUserData("mongodb://root:usestudio-1@123.58.32.151:11641?authSource=admin", "cocolog", "applog", {
- "2025-03-24": {
- "username":
- {
- userid: "",
- data: "",
- appname: "",
- status: ""
- }
- }
- });
- */
|