Sunday, 16 September 2018

[MongoDB] Is it possible to calculate a schema variable that keeps changing on real time based on other variables?

I'm sorry if this has been asked before but I couldn't find anything on the search engine. I just can't seem to find an answer or a way to do this easily. Here's the problem, I have 2 schemas: //Product Schema var mongoose = require("mongoose"); var productSchema = new mongoose.Schema({ comments: [ { type: mongoose.Schema.Types.ObjectId, ref: "Comment" } ], }); productSchema.methods.getAvg = function (grades) { return Math.round(grades.reduce(function (p, c) { return p + c; }) / grades.length); } module.exports = mongoose.model("Product", productSchema); And this one: var mongoose = require("mongoose"); var commentSchema = mongoose.Schema({ rating: Number, text: String, createdAt: { type: Date, default: Date.now }, }); module.exports = mongoose.model("Comment", commentSchema); So basically, every product contains comments, and every comment contains rating, text and a creation date.The product schema also has a method that calculates the average of an array so that I can print it in the views files easily without having to do much, but it is still not enough and it seems very unpractical, I have to do the following to print them: <% let ratings = []%> <% product.comments.forEach(function (comment) {ratings.push(comment.rating)}); %>
(<%= product.getAvg(ratings) %> average based <%= product.comments.length %> product <%= product.comments.length === 1 ? "review" : "reviews" %>) I grabbed this script for the input in case it creates some doubts: https://ift.tt/1j6O8Ui. In short, it basically displays 5 stars which can be used to upload something, and the no-rating is there to disable hover in case I want to use it for something else (like just displaying overall results, which is what I'm doing with value="<%= product.getAvg(ratings) %>").But as you can see this is pretty bad and annoying, I'd like to skip the forEach loop on product.comments and just add a <%= product.ratings %>, and ideally this product.ratings object should update itself from the other product.comments ratings, is it even possible?I've thought about adding another schema for the ratings, but then what? I just have no idea what to do.Thanks in advance reddit!EDIT: Oh and by the way, I'm using .ejs files for my views so that's why the <% %> brackets are present

Submitted September 16, 2018 at 09:54PM by -zerocreativity

No comments:

Post a Comment