【问题标题】:how should i make my database fetch continously我应该如何让我的数据库连续获取
【发布时间】:2021-11-07 23:08:51
【问题描述】:
function shield() {
  setInterval(async function () {
    const ProfileModelS = require("../models/ProfileSchema");
    await ProfileModelS.find({}).then((doc) => {
      doc.forEach(async (u) => {
        if (u.ShieldPoints <= 0) return console.log(u.Name);
        if (u.ShieldPoints > 0) {
          await ProfileModelS.findOneAndUpdate(
            { userID: u.userID },
            {
              $inc: {
                ShieldPoints: -1,
              },
            },
            console.log("done")
          );
        }
      });
    });
  }, 1000);
}

module.exports = shield

我希望我的 mongodb 在每个 Interval 上获取模型,但它没有这样做,每当我运行我的代码时它会获取模型,例如,它会获取 [{name: 'Joseph' , Points: 10}, {name: 'carman' , Points: -1}, {name: 'thee' , Points: 2}] 根据代码,它不会适当地减少点小于0的对象的点, 但它会继续减少超过0的对象点,如果对象点达到0,我希望它停止减少点,它应该继续减少点大于0的对象的点

简而言之,一旦特定对象的点达到 0,就应该停止该过程

【问题讨论】:

  • 将第二个 if 更改为 else 并尝试

标签: database mongodb discord discord.js bots


【解决方案1】:

您可以尝试使用Promise.all 来迭代所有检索到的模型,因为您似乎希望使用ShieldPoints &gt; 0 对每个实例执行async 操作,并且您的findOneAndUpdate 操作彼此独立。


function shield() {
  // Import the model schema
  const ProfileModelS = require("../models/ProfileSchema");

  setInterval(async function () {
    // Retrieve all models
    const users = await ProfileModelS.find();
    
    // Parallelise the process of updating the models that need to be updated
    Promise.all(
      users.map(async (user) => {
        if (user.ShieldPoints > 0) {
          await ProfileModelS.findOneAndUpdate(
            { userID: user.userID },
            {
              $inc: {
                ShieldPoints: -1,
              },
            },
          );
        };
      })
    );
  }, 1000);
}

module.exports = shield

但是,如果您的 findOneAndUpdate 操作未在 1000ms 间隔内完成,则代码将为这些相同的模型实例发出第二个 findOneAndUpdate 操作。这可能会导致您的模型多次更新,这是意外行为。要解决这个问题,您需要添加某种形式的防范措施。

【讨论】:

  • 感谢您的关注,但您的代码落后于我的整个系统,我想现在我应该创建一个不同的基础项目来处理这个项目,我的意思是像一个秘密网络或 smh
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多