D
D
Devero972021-02-07 17:11:22
Node.js
Devero97, 2021-02-07 17:11:22

How to update data using aggregate?

There is this code:

reviewSchema.statics.getAverageRating = async function(card) {
  console.log(card);
  const obj = await this.aggregate([
    {
      $match: { card: card }
    },
    {
      $group: {
        _id: "$card",
        averageRating: { $avg: "$rating" },
        ratingParams: { $avg: "$ratingParams" }
      }
    }
  ]);

  try {
    await this.model("cards").findByIdAndUpdate(card, {
      averageRating: obj[0].averageRating,
      ratingParams: obj[0].ratingParams
    });
  } catch (err) {
    console.log(err);
  }
};


When a review is created, another collection is searched and the data changes, as I understand it. The problem is that it only works like this (with one parameter)
reviewSchema.statics.getAverageRating = async function(card) {
  console.log(card);
  const obj = await this.aggregate([
    {
      $match: { card: card }
    },
    {
      $group: {
        _id: "$card",
        averageRating: { $avg: "$rating" }
      }
    }
  ]);

  try {
    await this.model("cards").findByIdAndUpdate(card, {
      averageRating: obj[0].averageRating
    });
  } catch (err) {
    console.log(err);
  }
};

But I need to update 2 parameters. But when saving, one parameter is changed, and the other becomes null. The thing is that I am passing an object as the second parameter. Perhaps this is causing an error? How to process it correctly?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question