Az Emna
Az Emna

Reputation: 535

Mongoose : Add an element to an array of Objects under an Object field

I'm trying to add an element to an array of Objects under an Object field This in my mongoose "Utilisateur" schema: enter image description here

So what i'm trying to do here is to add an element to the "lien_vers" array this is the code that i wrote

  Utilisateur.findOneAndUpdate({ _id: mongoose.Types.ObjectId(auteur._id) },

                          {
                            $push: {
                              'relations.lien_vers': {
                                metadonnees: { nom_societe: societePersonalId },
                                identite: auteur._id.toString(),
                                canons: [""]

                              }
                            }
                          }, { upsert: true }
                          , function (error, doc) {
                            if (err) {
                              console.log("Something wrong when updating data!", err);
                            }

                            console.log("updated", doc.relations);
                          });

i've got no errors but there is no changes ! it seems like the update is not working correctly Any help plz

Upvotes: 0

Views: 45

Answers (2)

Az Emna
Az Emna

Reputation: 535

Eventually this solution worked for me

I insist on adding markModified() so that the save() method can detect changes

  Utilisateur.findOne({ _id: mongoose.Types.ObjectId(auteur._id) }, function (err, sal) {
                          if (err) return handleError(err);
                          else {


                            sal.relations.lien_vers.push({
                              metadonnees: { nom_societe: societePersonalId },
                              identite: auteur._id.toString(),
                              canons: [""]
                            });

                            console.log("before saving", sal.relations.lien_vers)
                            sal.markModified('relations');
                            sal.save(function (err) {
                              if (err) {
                                console.log(err)
                              }
                              console.log("doc saved")
                            });




                          }

                        });

                      }

Upvotes: 0

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

By default, findOneAndUpdate() returns the document as it was before update was applied. If you set new: true, findOneAndUpdate() will instead give you the object after update was applied.

Your code looks fine, the record is updated in your db, it just return the document before update in your callback. To get the updated document, you just need to add new: true to the options.

Upvotes: 1

Related Questions