A
A
Annalana2021-08-16 19:07:42
Mongoose
Annalana, 2021-08-16 19:07:42

Why is the collection object not saved after the change?

Good afternoon everyone!
I'm trying to save (with change) a collection object. For some reason, the object remains in its previous form. Similar code in another function works, the .save method fires inside findOne.
At first I thought about asynchrony, but right before saving, in the line console.log(result.orderReplies); - the conclusion is absolutely correct, necessary, with changes. Saving gives "Success".
I understand that I’m stupid somewhere, but I can’t understand where, I double-checked everything more than once.
I believe that there will be a lot of comments on the code as a whole, and I will gladly listen to them.
Thanks a lot!

function send_message(value, req, res){
  let messagereply = req.body.reply;
  let newmessage = {messageUser: value, messageText: req.body.messageText, messageDate: new Date()};
  MODELS.OrderModel.findOne({orderID: req.body.orderID}, function(error, result){
    if (error) {
      res.send("Ошибка базы данных. Попробуйте снова или обратитесь к Администрации")
    }
    result.orderReplies.forEach((item, index, array) => {
      if (item.replyUser == messagereply) {
        let b = item.replyMessages;
        b.push(newmessage);
        item.replyMessages = b;
        console.log(item)
      }
    })
    console.log(result.orderReplies);
    result.save(function(err) {
      err ? console.log(err) : console.log("Успех")
    });
    res.redirect("/my_orders")
  })
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2021-08-16
@Annalana

must be used markModifiedsince you are modifying a nested object
result.markModified('orderReplies');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question