How to count URL visit in Nodejs , express?

Viewed 547

I am trying to make this basic CRM and here i need to see how many times the link has been visited by the client! is there any way i can do that and store ?

1 Answers

Actually I did this, as Ravi Teja said comment.

Added userClicks in the database model in case of mongoose.

(This is nested into another object)

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

When any request hits to that URL, I just update that count by one.

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);
});

});

You can do this by newer async-await syntax. From the above's code snippet, we will get idea, How to implement it.

Related