S
S
seregindev2018-04-09 20:08:34
MongoDB
seregindev, 2018-04-09 20:08:34

How to change the data of an array nested in an object?

Good day, I ran into a problem: I can't change the data of arrays nested in an object and accessible by key. Need to change arrays in subEvents
Code

exports.addVisitor = (req, res) => {
  const { visitorId, eventId, subEvents } = req.body;

  Event.findById(eventId, (err, event) => {
    if (err) return res.status(500).send({ message: "Error finding note with id " + eventId });

    //принимаю объект, в котором хранятся ключ: булвое значение
    //если всё ок, то мы пушим айду в наш массив
    for (let subEvent of Object.keys(subEvents)) {
      if(subEvents[subEvent]) {
        event.subEvents[subEvent].push(visitorId);
      } else {
        event.subEvents[subEvent].filter(ev => ev != visitorId);
      }
    }
    event.visitors.push(visitorId);

    event.save((err, event) => {
      if (err) return res.status(500).send({ message: "Error finding note with id " + eventId });

      res.send(event);
    })
  })
}

Database Schema and Example Instance5acb9dcb3ec83362751691.png5acb9dd884f6c829199885.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Abigovor, 2018-04-09
@Abigovor

You need to get a regular js object from the model.
This can be done in the following ways:
1. Call the toObject() method, and then change the docs
link object: mongoosejs.com/docs/api.html#document_Document-toObject
2. Call the .lean() method, which will allow mongoose to return a regular js object
example MyModel.findOne().lean().exec(function(err, doc) {
...
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question