0

I am a beginner of mongodb and express, now I am trying to update some data. I do not think there is something wrong in my code, when I turn debugging on, the following db operation is printed out and does not return any error from catch, therefore without any doubt, I thought the following update is executed without fail. Even I tested with the following update statement directly from mongo client tool, it worked fine. However it is not reflected on the actual database if I update from express. If updating is not successful, it should return some error, but it does not. Could you anyone give me some advice for this? I really do not know what is happening here, the following db operation works well from the mongo client tool. From express, it does not return error also. So, I come to ask about this.

Mongoose: persons.findOneAndUpdate({ _id: ObjectId("5be6d1087594078eac687f19") }, { '$push': { hobbies: { '$each': [ 'TEST', 'SING', 'SWIM' ] } } }, { '$push': { skills: [ 'programming' ] }, upsert: false, projection: {}, returnOriginal: true })

router.post("/edit/:id", (req, res, next) => {
  var hobbies = req.body.hobbies.split(",");
  var skills = req.body.skills.split(",");

  Person.findByIdAndUpdate(
    req.params.id,
    // { $set: { name: req.body.name } }
    { $push: { hobbies: hobbies} },
    { $push: { skills: skills} }
  )
    .exec()
    .then(person=> {
      res.json(person);
    })
    .catch(err => {
      console.log("ERROR", err);
    });
});
Anna Lee
  • 909
  • 1
  • 17
  • 37
  • 1
    In addition to the missing `{ new: true }` your mulitple `$push` is also incorrect and should be:`{ $push: { hobbies: { $each: hobbies }, skills: { $each: skills } } }` – Neil Lunn Nov 14 '18 at 02:15
  • Thank you so much for your answer, I am sorry but, is there any way I can just replace whole array not pushing new element? What I mean is that I want to delete whole elements in hobbies and skills and then want to push new elements. Sorry but there is some ways for it? – Anna Lee Nov 14 '18 at 02:26
  • Replacing is done with `$set`. Probably not advisable though since other requests might be made to modify the same document. So if another request "replaces" with one additional item, the second firing request does not see that document state. This is why `$push` and `$pull` are generally preferable for such purposes. – Neil Lunn Nov 14 '18 at 02:27

0 Answers0