简体   繁体   English

Node.js 用于重置 mongoDB 文档的脚本未执行

[英]Node.js script to reset mongoDB documents doesn't execute

I have built a game (card game) for which I also collect stats (how many time each card has been dealt, used and won).我已经构建了一个游戏(纸牌游戏),我还收集了统计数据(每张纸牌被分发、使用和获胜的次数)。

After doing some testing, I would like to release it but before doing so, I would like to reset the stats which have been collected while I was testing.在做了一些测试之后,我想发布它,但在这样做之前,我想重置我在测试时收集的统计数据。

I wrote a script that should do that, but it stops executing after trying to retrieve all the documents.我写了一个应该这样做的脚本,但它在尝试检索所有文档后停止执行。 I am getting no errors though, so I am not sure why it isn't working.不过我没有收到任何错误,所以我不确定为什么它不起作用。

** I'm new to Node.js and this is actually my first time trying to write an "independent" script rather than something that is actually part of my backend API, so it's likely something really silly, can't figure out what though. ** 我是 Node.js 的新手,这实际上是我第一次尝试编写一个“独立”脚本,而不是我的后端 API 的一部分,所以它可能真的很愚蠢,但我不知道是什么。

This is the script:这是脚本:

const Answer = require("../models/answer");

const reset = async() => {
    console.log("Reset script has been called");

    try {
        console.log("Entered the try catch block");

        const allAnswers = await Answer.find();

        console.log("before logging all the answers");
        console.log("allAnswers", allAnswers);

        allAnswers.forEach(async(answer) => {
            answer.times_dealt = 0;
            answer.times_picked = 0;
            answer.times_won = 0;

            await answer.save();
            console.log("saved new answer", answer);
        });
    } catch (e) {
        console.log("failed because", e);
    }
};

reset();

In my package.json I have it set up like this:在我的 package.json 中,我设置如下:

"scripts": {
    "start": "node src/index.js",
    "dev": "nodemon src/index.js",
    "reset-stats": "node src/scripts/reset-answer-stats.js"
},

This is my answer model:这是我的回答 model:

const mongoose = require("mongoose");
const { answerSchema } = require("../schemas/answer");

const Answer = mongoose.model("Answer", answerSchema);

module.exports = Answer;

And this is the schema:这是模式:

const mongoose = require("mongoose");

// This is the schema for an answer object in the DB.
const answerSchema = new mongoose.Schema({
    body: {
        type: String,
        trim: true,
        required: true,
    },

    times_dealt: {
        type: Number,
        required: true,
    },
    times_picked: {
        type: Number,
        required: true,
    },
    times_won: {
        type: Number,
        required: true,
    },
}, {
    timestamps: true,
});

module.exports = { answerSchema };

My process is that I first run the server npm run dev and then in another console I run npm run reset-stats .我的过程是我首先运行服务器npm run dev然后在另一个控制台中运行npm run reset-stats

It prints Reset script has been called它打印Reset script has been called

and then Entered the try catch block然后Entered the try catch block

And then it just ends.然后它就结束了。 No other logs or any errors.没有其他日志或任何错误。

What wrong?怎么了?

EDIT:编辑:

I've updated my script to use updateMany as suggested but now it fails because it times out.我已经按照建议更新了我的脚本以使用 updateMany,但现在它失败了,因为它超时了。 This is my new code.这是我的新代码。

const Answer = require("../models/answer");

const reset = async() => {
    console.log("Reset script has been called");

    try {
        console.log("Entered the try catch block");

        await Answer.updateMany({}, {
            $set: {
                times_dealt: 0,
                times_picked: 0,
                times_won: 0,
            },
        });

        console.log("after updating all the answers");
    } catch (e) {
        console.log("failed because", e);
    }
};

reset();

And the error log I get is:我得到的错误日志是:

failed because MongooseError: Operation `answers.updateMany()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\Users\Yanay\Documents\Coding\cards\api\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:158:23)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)

I only have like 20 documents on my local environment in this collection (production has hundreds).在这个集合中,我的本地环境中只有大约 20 个文档(生产有数百个)。

I've also tried to write the updateMany call like this as I see in some tutorials but it still prints the same error:我也试过像在一些教程中看到的那样编写updateMany调用,但它仍然打印出相同的错误:

    await Answer.updateMany({}, {
    times_dealt: 0,
    times_picked: 0,
    times_won: 0,
});

Try one update query instead of this loop of multiple queries:尝试一个更新查询而不是这个包含多个查询的循环:

db.collection.updateMany({},
{
  $set: {
    times_dealt: 0,
    times_picked: 0,
    times_won: 0
  }
})

See how it works on the playground exampleplayground 示例中查看它是如何工作的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM