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)}); %>
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment