【问题标题】:Mongoose Incrament Increase Entire Object ArrayMongoose 增量增加整个对象数组
【发布时间】:2018-09-25 21:11:05
【问题描述】:

我正在尝试开始保存用户(对于不和谐机器人)的统计信息,例如命令使用情况等。

我想将所有内容保存在我的mongodb 中。基本上,我试图实现从保存用户命令使用的数组定期更新数据库的能力,然后在数据库上更新信息后清理/擦除。

我的架构如下:

const userStatsSchema = new Schema({
    _id: mongoose.Schema.Types.ObjectId,
    userID: String,
    commandUsage: {
        command1: {
            type: Number,
            default: 0
        },
        command2: {
            type: Number,
            default: 0
        },
        command3: {
            type: Number,
            default: 0
        },
        command4: {
            type: Number,
            default: 0
        },
        command5: {
            type: Number,
            default: 0
        }
    }
})
const UserStats = mongoose.model('global_users', userStatsSchema);

老实说,在一次更新它们时,我不知道从哪里开始。请记住,commandUsage 数组远不止于此,而且还在不断增长。

我需要单独增加每一个还是有更好的方法?

$inc: commandUsage: { command1: 5, command2: 8, command3: 2, command4: 0 }

任何帮助解决这个问题将不胜感激!

【问题讨论】:

  • 你能澄清一下这个问题吗?您总是想增加commandUsage 对象的所有字段吗?或者您知道要增加commandUsage 的哪个字段?

标签: javascript node.js mongodb mongoose mongodb-query


【解决方案1】:

您可以使用bulk operations以固定间隔(时间或发生次数)执行

const UserStats = mongoose.model( 'global_users' );
const bulk = UserStats.collection.initializeOrderedBulkOp();
const maxNbrOfCommandAtOnce = 1000; // if you want to use an interval based on the nbr of commands
const interval = 10000; // to set an interval  of 10 sec

let saveBulkInterval = setInterval(executeBatch, interval);

const onCommand = function(event) {
    // I guess here that you have the ID of the item you to modify
    bulk.find({_id: itemId}).update({$inc: {event.commandName: 1}});

    if (bulk.s.currentBatchSize === maxNbrOfCommandAtOnce)
        executeBatch();
};

const executeBatch = function() {
    if (bulk.s.currentBatchSize > 0) {
        bulk.execute(function() {
            bulk = UserStats.collection.initializeOrderedBulkOp();
        });
    }
};

【讨论】:

  • 这似乎无法回答问题。
猜你喜欢
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 2015-06-03
  • 2021-10-10
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多