I am trying to update my database using the get method, the reason behind updating the DB using the get method is because when the get method will be called a value will be increased automatically.
This is my code where I am trying to update the database inside the get method. It's possible by mongoose but I am using raw MongoDB to update it. is it possible to update? or any other way to update it automatically when /:shortUrl
will be requested into the server.
app.get('/:shortUrl', async (req, res) => {
const filter = {
short: req.params.shortUrl
}
const updateDoc = {
$inc: {
clicks: 1
}
}
const urlDoc = await bicycleAffiliateLinksCollection.findOneAndUpdate(filter, updateDoc, {
new: false,
upsert: true
})
console.log(urlDoc.value.short)
res.redirect(`${urlDoc.value.full}?ref=${req.params.shortUrl}`)
res.send({
shortLink: urlDoc.value.short
})
})
CodePudding user response:
You can use $inc
operator instead. Try refactoring the code as shown below:
app.get('/:shortUrl', async (req, res) => {
const filter = {
short: req.params.shortUrl
}
const updateDoc = {
$inc: {
clicks: 1
}
}
const urlDoc = await bicycleAffiliateLinksCollection.findOneAndUpdate(filter, updateDoc, {
new: true,
upsert: true
})
console.log(urlDoc)
res.send({
shortLink: urlDoc.short
})
})
upsert
will create a new document if missing and new
will return contents of the new document.