Saturday 25 April 2020

Pulling single field from mongoDB query

Hey guys so I'm very much a noob when it comes to this stuff.I'm working on a course project creating a very simple google cloud function that will operate with a web front end. All I'm doing is running an aggregation to get the average of a particular field grouping and I want to then send that back to the database.I'm getting stuck on attempting to pull the single field from the average aggregation, I've found I need to use JSON.stringify() and then JSON.parse() but I'm getting an error saying that my query has circular logic. I do not see where it is really getting that from but nonetheless thats why I'm here asking for help.Here is the code in question (please be nice I'm new to this haha) (i've bolded what is the relevant section)const co = require('co');const mongodb = require('mongodb');const uri = 'mongodb+srv://USERNAME:[PASSWORD@cluster-gpld2.gcp.mongodb.net](mailto:cafuba101@cluster-gpld2.gcp.mongodb.net)/test?retryWrites=true&w=majority';exports.calculateRating = (req, res) => {  co(function*() {const client = yield mongodb.MongoClient.connect(uri);let userID = req.body.userID || req.query.userID;let submittedRating = req.body.submittedRating || req.query.submittedRating;let steamID = req.body.steamID || req.query.steamID;//check if user has rated the game beforeconst count = yield client.db('Games').collection('ratings').find({"steam_appid": parseInt(steamID), "user": userID}).count();//if the user has rated the game update their rating instead of making a new ratingif(count >= 1){      client.db('Games').collection('ratings').update({"steam_appid": parseInt(steamID), "user": userID}, {$set: {"rating": parseInt(submittedRating)}});//calculate average ratingconst averageJSON = client.db('Games').collection('ratings').aggregate([{$match: {'steam_appid': parseInt(steamID)}}, {$group: {_id: '$steam_appid', ratingAverage: {"$avg": "$rating"}}}]);const averageString = JSON.stringify(averageJSON);const result = JSON.parse(averageString);//insert average into games collection      client.db('Games').collection('Game_Info').update({"steam_appid": parseInt(steamID)}, {$set: {"rating": parseInt(result.ratingAverage)}});res.send('Your rating has been updated to: ' + submittedRating + result);}//otherwise make new rating else{//insertionyield client.db('Games').collection('ratings').insertOne({"steam_appid": parseInt(steamID), "user": userID, "rating": parseInt(submittedRating)});//TODO: calculate average rating      res.send('Your rating of ' + submittedRating + ' has been submitted. ' + JSON.stringify(average.ratingAverage));    }  }).catch(error => {    res.send('Error: ' + error.toString());  });};

Submitted April 26, 2020 at 12:04AM by TyranoMike

No comments:

Post a Comment