0

I have two models: Question and Answer. when an answer document is created, its reference question document's answerCount field increase by 1.

question model:

title: {
    type: String,
    required: true,
    unique: true,
  },
  content: {
    type: String,
    required: true,
  },
  
  createdAt: {
    type: Date,
    default: Date.now,
  },
  user: {
    type: mongoose.Schema.ObjectId,
    required: true,
    ref: "User",
  },
  answers: [
    {
      type: mongoose.Schema.ObjectId,
      ref: "Answer",
    },
  ],
  answersCount: {
    type: Number,
  },

and answer model:

content: {
    type: String,
    required: true,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  user: {
    type: mongoose.Schema.ObjectId,
    ref: "User",
    required: true,
  },
  question: {
    type: mongoose.Schema.ObjectId,
    ref: "Question",
    required: true,
  },

answer hook:

AnswerSchema.pre("save", async function (next) {
  if (this.isNew) {
    try {
      const question = await Question.findById(this.question);
      await question.answers.push(this._id);
      question.answersCount = question.answers.length
      await question.save();
    } catch (err) {
      throw new CustomError(err, 400);
    }
  }
  next();
});

when I run Answer.create([for example ten answer for same question]), question's answersCount field will be 9. But I expect it will be 10

or

when I run Answer.crate([two answers for each question]), all questions' answersCount field will be 1. But I expect they will be 2.

I don't understand why?

0 Answers0