I am struggling to merge two objects the way I need them using Node.js express and mongoDB. Below you will see both initial objects.
Obj1: {
"name":"max",
"age":26,
"hometown": "NY"
}
Obj2: {
"id": "123",
"favoriteteams" : ["Yankees, "Knicks"],
"home" : "NY"
}
I am currently trying:
const merged = {...obj1, ...obj2.favoriteteams};
But that gives me
merged: {
0: "Yankees"
1: "Knicks"
"name":"max",
"age":26,
"hometown": "NY"
}
But what I need is:
merged: {
"name":"max",
"age":26,
"hometown": "NY"
"favoriteteams": ["Yankees", "Knicks"];
}
I also have tried const merged = {...obj1, ...obj2}; and using Object.assign() but both obviously then mesh in the fields I don't need from obj2 (ID and home). Effectively I only need to get the favoriteteams from the second object, but I need that to be a new key in the first object and also to maintain the array response with the list of strings.
Thank you for any help.
You can leverage $mergeObjects in MongoDB aggregation.
db.collection.aggregate([
// keep only the fields you want in obj2
{
"$project": {
favoriteteams: 1
}
},
{
"$addFields": {
obj2: "$$ROOT",
obj1: <put your obj1 here>
}
},
{
"$project": {
// perform merge
merged: {
"$mergeObjects": [
"$obj1",
"$obj2"
]
}
}
},
{
"$replaceRoot": {
// revert back to original form
"newRoot": "$merged"
}
}
])
Here is the Mongo playground for your reference.