Good morning everyone!
I'm developing an application with Node.js and Angular, and I'm getting a little stuck lately.
I need to append a custom key -> value to an existing query result collection.
This is the function I have:
exports.findAll = (req, res) => {
Project.findAll({
include: [{
all: true,
include: [{
all: true
}]
}]
})
.then(data => {
data.forEach(
(project) => {
// <-------- HERE GOES THE APPEND
}
);
res.send(data);
})
.catch(err => {
res.status(500).send({
message: err.message || "Error retrieving projects"
});
});
};
Description:
After getting the result from the model query, I iterate over each result (aka Project).
Then, what I need to do is append a key -> value pair to that very Project.
By now, I'd like to do something like this:
exports.findAll = (req, res) => {
Project.findAll({
include: [{
all: true,
include: [{
all: true
}]
}]
})
.then(data => {
data.forEach(
(project) => {
project.cat = "miaw";
}
);
res.send(data);
})
.catch(err => {
res.status(500).send({
message: err.message || "Error retrieving projects"
});
});
};
This try hasn't made any changes in my JSON collection, and I don't know how to accomplish it neither.
Could someone give me some help? I've searched everywhere but couldn't find anything useful.
Thank you so much!
You just need to get plain objects from model instances and then you can add whatever you need to:
const projects = data.map(x => x.get({ plain: true }))
projects.forEach(
(project) => {
project.cat = "miaw";
}
);
res.send(projects);