【问题标题】:Mongodb collection not updating properly after webscraping new values网络抓取新值后,Mongodb 集合未正确更新
【发布时间】:2019-08-25 04:38:56
【问题描述】:

在一个网页抓取机器人上工作,当用户在不和谐聊天中使用 !stats 时,它会显示他们使用 Cheerio 从网站上抓取的统计信息。每次调用该命令时,都会抓取该站点并提取新的统计信息。但是问题是我在更新 mongodb 中的新值时遇到了困难,请参阅已评论的 console.logs 以了解该问题。任何帮助将不胜感激,感觉就像我错过了一些超级简单的东西。我试过 find、findOne 和 findOneAndUpdate 都遇到同样的问题。

Stats.find({}, 'userId', { '_id': 0 }, function (err, docs) {

        for (i = 0; i < docs.length; i++) {
            ids.push(docs[i].userId);
        }

        /////

        ids.forEach(function (entry) {
            var userUrl = 'https://popflash.site/user/' + entry;



            rp(userUrl)
                .then(function (html) {
                    const arr = [];
                    var e = 0;

                    $('.stat-container', html).each(function (key, value) {
                        arr[e++] = $(this).find(".stat").text();

                    });



                    var results = arr.map(Number)
                   console.log(results); //this is printing the newly scraped stats from the site which is working fine.

                    var query = { userId: entry };

                    Stats.find(query, {
                        $set: {
                            HLTV: results[0],
                            ADR: results[1],
                            HS: results[2],
                            W: results[3],
                            L: results[4],
                            T: results[5],
                            totalGames: results[3] + results[4],
                            win_percent: results[6]
                        }
                    })
                        .then(function (result) {

                                    console.log(result) //this is displaying old stats that are stored in the db, seems to not be updating.
                        })

                })
        }); 

    });

【问题讨论】:

    标签: mongodb mongoose discord.js cheerio request-promise


    【解决方案1】:

    您正在运行find 查询,当然结果将是数据库中已有的内容。如果要update db,则需要使用update 方法。

    Stats.update(query, {
       $set: {
           HLTV: results[0],
           ADR: results[1],
           HS: results[2],
           W: results[3],
           L: results[4],
           T: results[5],
           totalGames: results[3] + results[4],
           win_percent: results[6]
       }
    })
    

    【讨论】:

    • 大声笑,我想我已经把事情复杂化了,对 mongodb 来说是新手。成功了,谢谢大佬!
    • @tru2793 将来,我建议阅读 mongo 文档...或在“mongo 如何更新文档”的行中搜索一些内容。同时,如果这确实是您问题的解决方案,请接受我的回答。
    • 如果答案对您有帮助并解决了问题,请按答案旁边的绿色勾号将您的问题标记为已解决。
    猜你喜欢
    • 2017-11-09
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多