want to show average rating and total reviews of product - mongodb

I am beginner and following a tutorial to make a review products application and rather than just copy pasting the code trying to do some experiment with it to get more depth knowledge. I have two questions regarding my app
1) I added some more functionality to my app and wrote some code in includes.js and reviews.html to show average rating and total review of a product .How i can show average rating and number of reviews for the product thats been clicked?
2) I added product categories list to show in side bar(e.g Electronics , Fashion, Books) through chrome console by adding them manually e.g like this
Categories.insert({name:'Eelctronics',slug:'electronics'});
So i have deployed this app on free meteor hosting and every time some one run this app he has to write this above code manually in chrome console to get list of categories.Even if some one clone my project from gitHub also can not see list of categories in left side bar and he also have to write the same code in console.So what is the solution for it how i can show list of categories in my side bar with out writing above code in console?
You can check gitHub repository for source code.

1) Show average rating and review count
<p>Average Rating: <img class="stars" src="/img/star{{averageRating}}.png"> ({{countReviews}})</p>
I've moved this code into reviews.helpers section
Template.reviews.helpers({
'reviews': function () {
return Reviews.find({productId: Router.current().data()._id})
},
countReviews: function(){
return Reviews.find({productId: Router.current().data()._id}).count();
},
averageRating: function() {
var reviews = Reviews.find({productId: Router.current().data()._id}); //get all reviews for productId
//var ratings = reviews.map(function(player){return player.score;}); // get just the ratings, or use _.pluck
var ratings = _.pluck(reviews, 'ratings'); // get just the ratings i.e. [1, 5, 3, 2, 5]
var sum = ratings.reduce(function(pv, cv){return pv + cv;}, 0); //sum ratings i.e. 14
var avg = sum / ratings.length; // i.e. 2.8
return Math.round(2.8); // round avg to ensure only integer values are returned
},
})
2) Seed database
Docs Add a Meteor.startup block to seed database
// On server startup, if the database is empty, create some initial data.
if (Meteor.isServer) {
Meteor.startup(function () {
if (Categories.find().count() === 0) {
Categories.insert({name:'Electronics',slug:'electronics'});
Categories.insert({name:'Fashion',slug:'fashion'});
Categories.insert({name:'Books',slug:'books'});
}
});
}

Related

Faster way to get delta of 2 collections in Mongo

I have a complete list of catalog inventory data in Mongo
The basic schema is:
productSku (string)
inventory (number)
This collection consists of approximately 14 million records.
I have another list of actively sold products with a similar schema.
Right now I have it as a json file.
It consists of approximately 23,000 records.
Every 5 hours the 14 million records updates with the latest inventory data.
Once that happens I need to create a CSV of the 23,000 product's latest inventory.
I'm doing it like this:
const inventoryModel = require('../data/inventoryModel');
const activeProducts = require('./activeProducts.json');
const inventoryUpdate = [];
for (const product of activeProducts) {
let latest = await inventoryModel.findOne({ productSku: product.sku }).exec()
latest = latest ? latest._doc : null;
// If there's no current inventory record for the product
if (!lastest) {
// If there was previously an inventory greater than 0
if (product.inventory) {
// Set the latest inventory to you
inventoryUpdate.push({ sku: product.sku, inventory: 0 });
}
} else {
// If there's a change in inventory
if (latest.inventory != product.inventory) {
inventoryUpdate.push({ sku: product.sku, inventory: latest.inventory });
}
}
}
This gives me an array inventoryUpdate that I can use to create a CSV for a mass update. This works fine but it's very slow. It takes about an hour to complete!
I was thinking about maybe adding activeProducts to Mongo as well and if I can somehow keep the execution of the logic within Mongo this would be a lot faster. If possible this is beyond my current understanding and ability.
Anyone have any suggestions?

Hierarchial JSON model and UI5

I am creating a demo application with JSON data and UI5. The idea (in a nutshell) is provide various information views for a selected item. I am using IconTabBar control. I have created an example scenario so (hopefully) I can explain the problem more clearly.
1.IconTabBar's first tab has list of employees and user can select one by selecting a radio button on the left
2.This takes the user to the next tab that displays say, sales view. The user can click on any tab and move to the respective view.
3.User can modify the information in any view. If the users forgets or ignores to Save the data, the tab color is set to Red.
4.User can Save the data.
5.Some of the views have information in master detail format.
The problem(s) I am facing are:-
1.How to filter the model data based on the item selected in the table?
2.How to update the filtered data and set back to model?
3.I also would like to know whether the data is structured correctly
I am using following code to update the binding path after company is selected. The GREP function is not returning correct values for proposals. It returns ONLY 1 proposal for E001 whereas it should return 2. It doesn't work properly for orders either. I am not sure whether the data is structured correctly.
var oModel_Data = oJSONDataModel.getData();
var oView_Data = oViewDataModel.getData();
var aModelData = oModel_Data[sSelected_Key];
var aViewData = oView_Data[sSelected_Key];
aViewData = jQuery.grep(aModelData, function(data, index) {
return data.id === sSelected_id
})[0];
oView_Data[sSelected_Key]=aViewData;
oViewDataModel.setData(oView_Data);
oViewDataModel.refresh(true);
I am using following code to check whether user has changed data.
var oView_Data = oViewDataModel.getData();
var oModel_Data = oJSONDataModel.getData();
var aViewData = oView_Data[in_sKey];
var aModelData = oModel_Data[in_sKey];
aModelData.forEach(function(item, index, array) {
var valueView = aViewData;
if (item.id === sSelected_id){
//The code here need to consider complex(nested) data types
//Thus it should check type of not only valueView and item
//but also their each and every child elements
/*---------Temporary Solution---------------------*/
var sViewValue = JSON.stringify(valueView);
var sItem = JSON.stringify(item);
var bSameData = sViewValue === sItem;
if (bSameData==true){
flag_data_changed=false;
}else{
return flag_data_changed=true;
}
}
});
My json model is as below.
{
"employees": [
{"id":"E0001" ,
"name":"Alec Stewert"
},
{"id":"E0002" ,
"name":"Debra Manning"
}
],
"sales": [
{"id":"E0001" ,
"sale_q1":"10000",
"sale_q2":"3000",
"sale_q3":"8000",
"sale_q4":"2000"
},
{"id":"E0002" ,
"sale_q1":"8000",
"sale_q2":"3000",
"sale_q3":"7000",
"sale_q4":"5000"
}
],
"proposal":[
{"id":"E0001",
"fi_q":"Q2",
"value":"12000",
"customer":"6000"
},
{ "id":"E0001",
"fi_q":"Q2",
"value":"8000",
"customer":"2300"
}
],
"key_orders": [
{"id":"E0001",
"order_hdr":
[
{"id":"O0001",
"fi_q":"Q1",
"value":"2000",
"customer":"2000"
},
{"id":"O0002",
"fi_q":"Q1",
"value":"2000",
"customer":"2000"
}
],
"order_dtl":[
{
"id":"O0001",
"itm":"Item X",
"Qty":"100",
"rate":"20"
}
]
},
{"id":"E0002",
"order_hdr":
[
{"id":"O0011",
"fi_q":"Q1",
"value":"2000",
"customer":"5000"
},
{"id":"O0012",
"fi_q":"Q1",
"value":"1000",
"customer":"5000"
}
],
"order_dtl":[
{
"id":"O00011",
"itm":"Item Z",
"Qty":"200",
"rate":"10"
}
]
}
]
}
I have investigated online and in SAP Help but failed to understand what needs to be done. Any help is appreciated.
1.How to filter the model data based on the item selected in the table?
If you prepare the JSONModel you can use the Filter
2.How to update the filtered data and set back to model?
If you bind the table to the JSONModel, by default the JSNOModel is 2 way binding so any edited data will be in the JSONModel
3.I also would like to know whether the data is structured correctly
Go through the Example of the Table So you will get an idea of the Model and binding model to the Table

How do I publish two random items from a Meteor collection?

I'm making an app where two random things from a collection are displayed to the user. Every time the user refreshes the page or clicks on a button, she would get another random pair of items.
For example, if the collection were of fruits, I'd want something like this:
apple vs banana
peach vs pineapple
banana vs peach
The code below is for the server side and it works except for the fact that the random pair is generated only once. The pair doesn't update until the server is restarted. I understand it is because generate_pair() is only called once. I have tried calling generate_pair() from one of the Meteor.publish functions but it only sometimes works. Other times, I get no items (errors) or only one item.
I don't mind publishing the entire collection and selecting random items from the client side. I just don't want to crash the browser if Items has 30,000 entries.
So to conclude, does anyone have any ideas of how to get two random items from a collection appearing on the client side?
var first_item, second_item;
// This is the best way I could find to get a random item from a Meteor collection
// Every item in Items has a 'random_number' field with a randomly generated number between 0 and 1
var random_item = function() {
return Items.find({
random_number: {
$gt: Math.random()
}
}, {
limit: 1
});
};
// Generates a pair of items and ensure that they're not duplicates.
var generate_pair = function() {
first_item = random_item();
second_item = random_item();
// Regenerate second item if it is a duplicate
while (first_item.fetch()[0]._id === second_item.fetch()[0]._id) {
second_item = random_item();
}
};
generate_pair();
Meteor.publish('first_item', function() {
return first_item;
});
// Is this good Meteor style to have two publications doing essentially the same thing?
Meteor.publish('second_item', function() {
return second_item;
});
The problem with your approach is that subscribing to the same publication with the same arguments (no arguments in this case) over and over in the client will only get you subscribed only once to the server-side logic, this is because Meteor is optimizing its internal Pub/Sub mechanism.
To truly discard the previous subscription and get the server-side publish code to re-execute and send two new random documents, you need to introduce a useless random argument to your publication, your client-side code will subscribe over and over to the publication with a random number and each time you'll get unsubscribed and resubscribed to new random documents.
Here is a full implementation of this pattern :
server/server.js
function randomItemId(){
// get the total items count of the collection
var itemsCount = Items.find().count();
// get a random number (N) between [0 , itemsCount - 1]
var random = Math.floor(Random.fraction() * itemsCount);
// choose a random item by skipping N items
var item = Items.findOne({},{
skip: random
});
return item && item._id;
}
function generateItemIdPair(){
// return an array of 2 random items ids
var result = [
randomItemId(),
randomItemId()
];
//
while(result[0] == result[1]){
result[1] = randomItemId();
}
//
return result;
}
Meteor.publish("randomItems",function(random){
var pair = generateItemIdPair();
// publish the 2 items whose ids are in the random pair
return Items.find({
_id: {
$in: pair
}
});
});
client/client.js
// every 5 seconds subscribe to 2 new random items
Meteor.setInterval(function(){
Meteor.subscribe("randomItems", Random.fraction(), function(){
console.log("fetched these random items :", Items.find().fetch());
});
}, 5000);
You'll need to meteor add random for this code to work.
Meteor.publish 'randomDocs', ->
ids = _(Docs.find().fetch()).pluck '_id'
randomIds = _(ids).sample 2
Docs.find _id: $in: randomIds
Here's another approach, uses the excellent publishComposite package to populate matches in a local (client-only) collection so it doesn't conflict with other uses of the main collection:
if (Meteor.isClient) {
randomDocs = new Mongo.Collection('randomDocs');
}
if (Meteor.isServer) {
Meteor.publishComposite("randomDocs",function(select_count) {
return {
collectionName:"randomDocs",
find: function() {
let self=this;
_.sample(baseCollection.find({}).fetch(),select_count).forEach(function(doc) {
self.added("randomDocs",doc._id,doc);
},self);
self.ready();
}
}
});
}
in onCreated: this.subscribe("randomDocs",3);
(then in a helper): return randomDocs.find({},{$limit:3});

MongoDB Social Network Adding Followers

I'm implementing a social network in MongoDB and I need to keep track of Followers and Following for each User. When I search for Users I want to display a list like Facebook with the User Name, Picture and number of Followers & Following. If I just wanted to display the User Name and Picture (info that doesn't change) it would be easy, but I also need to display the number of Followers & Following (which changes fairly regularly).
My current strategy is to embed the People a User follows into each User Document:
firstName: "Joe",
lastName: "Bloggs",
follows: [
{
_id: ObjectId("520534b81c9aac710d000002"),
profilePictureUrl: "https://pipt.s3.amazonaws.com/users/xxx.jpg",
name: "Mark Rogers",
},
{
_id: ObjectId("51f26293a5c5ea4331cb786a"),
name: "The Palace Bar",
profilePictureUrl: "https://s3-eu-west-1.amazonaws.com/businesses/xxx.jpg",
}
]
The question is - What is the best strategy to keep track of the number of Followers & Following for each User?
If I include the number of Follows / Following as part of the embedded document i.e.
follows: [
{
_id: ObjectId("520534b81c9aac710d000002"),
profilePictureUrl: "https://pipt.s3.amazonaws.com/users/xxx.jpg",
name: "Mark Rogers",
**followers: 10,**
**following: 400**
}
then every time a User follows someone requires multiple updates across all the embedded documents.
Since the consistency of this data isn't really important (i.e. Showing someone I have 10 instead of 11 followers isn't the end of the world), I can queue this update. Is this approach ok or can anyone suggest a better approach ?
You're on the right track. Think about which calculation is performed more - determining the number of followers/following or changing number of followers/following? Even if you're caching the output of the # of followers/following calculation it's still going to be performed one or two orders of magnitude more often than changing the number.
Also, think about the opposite. If you really need to display the number of followers/following for each of those users, you'll have to then do an aggregate on each load (or cache it somewhere, but you're still doing a lot of calcs).
Option 1: Cache the number of followers/following in the embedded document.
Upsides: Can display stats in O(1) time
Downsides: Requires O(N) time to follow/unfollow
Option 2: Count the number of followers/following on each page view (or cache invalidation)
Upsides: Can follow/unfollow in O(1) time
Downsides: Requires O(N) time to display
Add in the fact that follower/following stats can be eventually consistent whereas the counts have to be displayed on demand and I think it's a pretty easy decision to cache it.
I've gone ahead and implement the update followers/following based on the same strategy recommended by Mason (Option 1). Here's my code in NodeJs and Mongoose and using the AsyncJs Waterfall pattern in case anyone is interested or has any opinions. I haven't implemented queuing yet but the plan would be to farm most of this of to a queue.
async.waterfall([
function (callback) {
/** find & update the person we are following */
Model.User
.findByIdAndUpdate(id,{$inc:{followers:1}},{upsert:true,select:{fullName:1,profilePictureUrl:1,address:1,following:1,followers:1}})
.lean()
.exec(callback);
},
function (followee, callback) {
/** find & update the person doing the following */
var query = {
$inc:{following:1},
$addToSet: { follows: followee}
}
Model.User
.findByIdAndUpdate(credentials.username,query,{upsert:true,select:{fullName:1,profilePictureUrl:1,address:1,following:1,followers:1}})
.lean()
.exec(function(err,follower){
callback(err,follower,followee);
});
},
function(follower,followee,callback){
/** update the following count */
Model.User
.update({'follows._id':follower.id},{'follows.$.following':follower.following},{upsert:true,multi:true},function(err){
callback(err,followee);
});
},
function(followee,callback){
/** update the followers count */
Model.User
.update({'follows._id':followee.id},{'follows.$.followers':followee.followers},{upsert:true,multi:true},callback);
}
], function (err) {
if (err)
next(err);
else {
res.send(HTTPStatus.OK);
next();
}
});

MongoDB - get 1 last message from each conversation?

I have a collection for conversations:
{_id: ..., from: userA, to: userB, message: "Hello!", datetime: ...}
I want to show a preview of user's conversations - last message from each conversation between current user and any other users. So when user clicks on some "last message" he goes to next page with all messages between him and that user.
How do I do that (get 1 last message from each conversation) without Map/Reduce?
1) use "distinct" command? (how?)
2) set "last" flag for last message? I think it's not very safe...
3) ..?
I was writing up a complicated answer to this question using cursors and a lot of advanced query features and stuff... it was painful and confusing. Then I realized, this is painful because it's not how mongodb expects you to do things really.
What I think you should do is just denormalize the data and solve this problem in one shot easily. Here's how:
Put a hash/object field on your User called most_recent_conversations
When you make a new conversation with another user, update it so that it looks like this:
previewUser.most_recent_conversations[userConversedWith._id] = newestConversation._id
Every time you make a new conversation, simply smash the value for the users involved in their hashes with the newer conversation id. Now we have a { uid: conversationId, ... } structure which basically is the preview data we need.
Now you can look up the most recent conversation (or N conversations if you make each value of the hash an array!) simply:
var previewUser = db.users.findOne({ _id: someId });
var recentIds = [];
for( uid in previewUser.most_recent_conversations ) {
recentIds.push( previewUser.most_recent_conversations[uid] );
}
var recentConversations = db.conversations.find({
_id: { $in: recentIds }
});