我的静态方法没有运行

时间:2017-07-05 19:41:06

标签: javascript node.js mongodb mongoose mongoose-schema

这是我的recipe.js文件...

const express = require('express');
const mongoose = require('mongoose');
const User = require('../model/user');
require('mongoose-currency').loadType(mongoose);
const Currency = mongoose.Types.Currency;
const Schema = mongoose.Schema;
const reviewSchema = require('../model/review');



let recipeSchema = new Schema({

  name: {
    type: String,
    required: true
  },

  description: {
    type: String,
  },

  steps: {
    type: String,
    required: true,
  },

  ingredients: {
    type: Array,
    default: ['1', '2', '3', '4']
  },

  category: {
    type: String,
    required: true,
    index: true
  },

  postedBy: {
    type: String,
    required: true,
  },


  reviewsOfRecipe: [reviewSchema],

  numberOfRatings: {
    type: Number,
    default: 0
  },

  totalAddedRatings: {
      type: Number,
      default: 0
  },

  reviewAverage: {
      type: Number,
      default: 0
  },

  postersCreationDate: {
    type: Number,
    index: true
  },

  likedBy: {
      type: Array

  },

  reviewedBy: {
      type: Array
  }


});

// Here is my static method

recipeSchema.methods.calculateAverage = function(){

  let recipe = this;

  if (recipe.numberOfRatings === 0  && recipe.totalAddedRatings === 0){
    recipe.reviewAverage = 0;
  }
  else {


    recipe.reviewAverage = recipe.totalAddedRatings / recipe.numberOfRatings


  }


};



let Recipe = mongoose.model('Recipe', recipeSchema);

module.exports = Recipe;

在我的路由器文件中,每次用户提交食谱评论时,字段numberOfRatingstotalAddedRatings都会递增。在它们增加之后,我的静态方法calculateAverage应该运行并更新文档。

以下是我的代码中的内容:

Recipe.findOneAndUpdate({_id: recipe._id, postersCreationDate: recipe.postersCreationDate},{$inc: {numberOfRatings: 1, totalAddedRatings: reviewScore}}, {returnNewDocument: true}).then((recipe) => {

               recipe.calculateAverage();
});

但是,每次用户提交评论时,虽然numberOfRatingsnumberOfRatings会相应增加,但reviewAverage却没有。

我正在考虑将reviewAverage设置为虚拟字段;但我担心这样做会使按最高和最低评价平均值对食谱进行排序变得更加困难和低效。

1 个答案:

答案 0 :(得分:0)

关于findOneAndUpdate的一些事情可以改变。 Id应该足以找到并且'returnNewDocument'不是一个选项。在猫鼬中它只是'新'

Recipe.findOneAndUpdate({_id: recipe._id},{$inc: {numberOfRatings: 1, totalAddedRatings: reviewScore}}, {new: true}).then((recipe) => {
    recipe.calculateAverage();
});

问题在于您没有将平均值保存到配方中。

recipeSchema.methods.calculateAverage = function(callback) {
  let recipe = this;
  if (recipe.numberOfRatings === 0  && recipe.totalAddedRatings === 0) {
      recipe.reviewAverage = 0;
  }
  else {
      recipe.reviewAverage = recipe.totalAddedRatings / recipe.numberOfRatings
  }
  recipe.save(callback);
};