How to modify data from mongodb?
I have data from mongobd by query:
ProfileModel.find(
{
_id: {
$in: [
'63a0488c88723874c1fb3fbf',
'63a04894d4bdd0a191b69573',
]
}
}
)
Original Data From MongoDB:
[
{
name: "Name",
image: "https//image......"
},
{
name: "Name",
image: "https//image......"
}
]
I want to modify Original Data From MongoDB like this:
data: [
{
type: "User",
attributes: {
name: "Name",
image: "https//image......"
}
},
{
type: "User",
attributes: {
name: "Name",
image: "https//image......"
}
}
]
CodePudding user response:
Not an entire clean solution, but this will get you on the right way. You could use Array.prototype.map()
function to create a new array using the original array you received from your database, see the following snippet:
const someDataArray = [
{
name: "Name",
image: "https//image......"
},
{
name: "Name",
image: "https//image......"
}
];
const newArray = someDataArray.map(item => {
return {
type: "User",
attributes: {
name: item.name,
image: item.image
}
};
});
console.log({ data: newArray });
CodePudding user response:
If you just want to modify the object after it has been loaded, you can use mogoose middleware you can find about it here
schema.post('init', function(doc, next) {
doc = doc.map(obj => ({ ...obj, type: 'User' }))
next();
});