node.js - 如何统计Nodejs中的URL访问量,express?

标签 node.js url

我正在尝试制作这个基本的 CRM,在这里我需要查看客户访问该链接的次数!有什么办法可以做到这一点并存储吗?

最佳答案

实际上我就是这么做的,正如 Ravi Teja 评论中所说。

在数据库模型中添加了userClicks(如果是 Mongoose )。

(嵌套到另一个对象中)

  analytics: {
        userClicks: {
            type: Number,
            default : 0
        }
    }

当任何请求到达该 URL 时,我只需将该计数更新为 1。

app.get('URL', (req, res) => {
//First find document in database
Url.findOne({
  $text: {
    $search: request.params.shortUrl
  }
}).then(url => {
  if (url === null) {
    return response.status(404).json({
      message: "Link in not valid"
    });
  } else {
    //If successfully found, get already stored value and updated with +1, and then update that document.
    const _id = url._id
    let counterClicks = url.analytics.userClicks;
    //Update existing values
    counterClicks++;
    Url.findByIdAndUpdate({
      _id
    }, {
        $set: {
          'analytics.userClicks': counterClicks
        }
      }).exec().then(url => {
        console.log(url);
        return response.redirect(302, url.originalUrl);
      }).catch(error => {
        console.log(error);
      });
  }
}).catch(error => {
  console.log(error);
});

});

您可以通过更新的 async-await 语法来完成此操作。 从上面的代码片段中,我们将了解如何实现它。

关于node.js - 如何统计Nodejs中的URL访问量,express?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63656052/

相关文章:

node.js - 使用 mongoose findOne/save 保存对象不起作用

node.js - 如何使用可选的快速查询参数编写 Mongoose 查询?

javascript - 打印所有mongoDB数据到字符串nodejs

c# - 使用正则表达式提取数据 url

java - 从 URL 下载文件到文件夹

javascript - NodeJS/jQuery - 投票通知 API

mysql - 如何将图像上传到mysql数据库并在pug模板引擎中显示来自mysql数据库的图像?

python-3.x - youtube-dl 只取 URL 的第一个字母?

javascript - "Undefined"有时出现在我的 ASP.NET 应用程序的 URL 中(不知何故与谷歌相关?)