Skip to content

Instantly share code, notes, and snippets.

@otoo-peacemaker
Last active May 1, 2023 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otoo-peacemaker/34c7c95648b3ce8f2f52609dea4b0f0e to your computer and use it in GitHub Desktop.
Save otoo-peacemaker/34c7c95648b3ce8f2f52609dea4b0f0e to your computer and use it in GitHub Desktop.
downloadCount
const collectionName = 'downloads';
// Create or update the document with the matching fileId
const fileId = '1234';
const downloadCount = 1;
const email = '';
// Options for findOneAndUpdate method
const options = { upsert: true, new: true };
// Query to find the document with the matching fileId
const query = { fileId };
// Update the 'downloadCount' and 'email' fields in the document with the matching fileId, or create a new document if one is not found
const update = { $inc: { downloadCount} };
// Use findOneAndUpdate to save the document
const savedDocument = await db.collection(collectionName).findOneAndUpdate(query, update, options);
console.log(`Document saved: ${savedDocument}`);
const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb+srv://<username>:<password>@<cluster-address>/test?retryWrites=true&w=majority';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function updateDownloadCount(fileId) {
try {
await client.connect();
const database = client.db('test');
const collection = database.collection('downloadedFiles');
const filter = { _id: fileId };
const update = { $inc: { downloadCount: 1 } };
const options = { upsert: true };
const result = await collection.findOneAndUpdate(filter, update, options);
console.log(`Download count updated for file with ID ${fileId}.`);
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}
updateDownloadCount('file123');
const express = require('express');
const router = express.Router();
const collectionName = 'downloads';
router.get('/downloads', async (req, res) => {
try {
const downloads = await db.collection(collectionName).find({}).toArray();
return res.send(downloads);
} catch (err) {
console.error(err);
return res.status(500).send({ message: 'Internal server error' });
}
});
module.exports = router;
@otoo-peacemaker
Copy link
Author

You can either try the first solution or the function.
Lemme know how it goes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment