Answer the question
In order to leave comments, you need to log in
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);
})
})
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question