Carlos Orelhas
Carlos Orelhas

Reputation: 73

UpdateOne mongodb without changing others objects

Let see the example below

MongoDB Schema

I want to update just one record inside my ExpensesHouse so I build the following code

router.post("/editExpense/:id", ensureAuthenticated, (req, res) => {
  var id = mongoose.Types.ObjectId(req.params.id);
  House.updateOne(
    { "expensesHouse._id": id },
    {
      $set: {
        expensesHouse: {
          _id: id,
          expenseType: req.body.expenseType,
          description: req.body.description,
          price: req.body.price,
          status: req.body.status,
          userID: req.user.id
        }
      }
    }
  ).then(house => {
    req.flash("success_msg", "Expenses Updated");
    res.redirect("/houses/dashboard");
  });
});

It works fine and can update the record, but since I have 2 or more Objects all the others gone. So when I update let suppose 1: Object, expenseType: Water and I change the type of expense to other, the 0: Object just disappear and I need to update only the register with the _id: id

Below you can see the result after UpdateOne

MongoDB Afeer Update

Upvotes: 1

Views: 381

Answers (1)

rpereira15
rpereira15

Reputation: 197

Try this:

router.post("/editExpense/:houseId/:id", ensureAuthenticated, (req, res) => {
  var id = mongoose.Types.ObjectId(req.params.id);
  var houseId : mongoose.Types.ObjectId(req.params.houseId);
  House.updateOne(
    { "_id": houseID, "expensesHouse._id": id },
    {
      $set: {
          expensesHouse.$.expenseType: req.body.expenseType,
          expensesHouse.$.description: req.body.description,
          expensesHouse.$.price: req.body.price,
          expensesHouse.$.status: req.body.status,
          expensesHouse.$.userID: req.user.id
        }
      }
    }
  ).then(house => {
    req.flash("success_msg", "Expenses Updated");
    res.redirect("/houses/dashboard");
  });
});

Upvotes: 1

Related Questions