0

My User Schema is like this

{
  _id:ObjectId("6e9465528a15ba6")
  name: 'XYZ',
  email: 'abc@gmail.com',
  transactions: [
    {
      _id:ObjectId("5e946557a5128a15ba6"),
      date: 2020-04-09T06:00:30.000Z,
      type: 'type1',
      category: 'category1',
      description: 'some desc',
    }
  ]
}

I want to update some fields of transaction with specific id. But not happening.

I tried the solution answered to Mongoose, update values in array of objects this question.

May be my _id is of type ObjectId and id coming from my request is String? So how can I solve this problem?

My code is like this but still getiing error user.transactions._id is not function

app.post('/api/update', function (req, res) {
  const {
    id,
    email,
    date,
    type,
    category,
    description
  } = req.body;

  User.findOne({email}, function (err, user) {
    if (err) {
      console.error(err);
      res.status(500)
        .json({
          error: 'Internal error please try again'
        });
    } else if (!user) {
      res.status(401)
        .json({
          error: 'Incorrect email or password'
        });
    } else {
      const objectId = mongoose.Types.ObjectId(id);
      let transaction = user.transactions._id(objectId);
      transaction.date = date;
      transaction.type = type;
      transaction.category = category;
      transaction.description = description;

      user.save((err, data) => {
        if (err) return res.send(err);
        return res.sendStatus(200);
      });
    }
  });
});
Tushar Tambe
  • 115
  • 1
  • 8

1 Answers1

0

fortunately I had to do something similar recently, so I suggest you to have a look at this page from Mongoose docs in the case I miss something, but basically you have to find the document first and then update its array of objects.

I'd try something like this:

User.findOne({ _id: your_user_id }, (err, data) => {
    if (err) return console.log(err);

    if (data) {

      //Mongoose has a special method (id) for subdocuments
      var transaction = data.transactions.id(your_transaction_id);
      date: new Date(),
      type: 'type2',
      category: 'category2',
      description: 'whatever',

      //data.save() saves everything, document and subdocument
      data.save((err, data) => {
        if (err) return console.log(err);
        done(null, data);
      });

    }