Reputation: 991
So while trying to update a document in mongoose, I realized that when I do obj.key=value
to a document I obtained with Model.findOne()
, it doesn'st assign the property to its value. But after trying obj.set(key, value), the property is assigned to its value in the document. So why is that? Usually when i do the first method to an object, the object gets the property. What is the .set()
function? Does it have something to do with mongoose?
//this works
async function updateItem(){
let updatedItem = await Item.findOne({name:req.body.itemName});
Object.entries(req.body).forEach(elem=>{
if(elem[0]!=="itemName"){
updatedItem.set(elem[0], elem[1]);
};
});
};
updateItem();
});
//this doesn't work
async function updateItem(){
let updatedItem = await Item.findOne({name:req.body.itemName});
Object.entries(req.body).forEach(elem=>{
if(elem[0]!=="itemName"){
updatedItem.elem[0] = elem[1];
};
});
};
updateItem();
});
Upvotes: 0
Views: 75
Reputation: 44107
It means that updatedItem
is not an object, it's a Map
, and to add items to a Map
you need to use the get
method.
Another thing to point out is that when you set updatedItem.elem[0]
, you're literally trying to add the key "elem[0]"
to updatedItem
. To fix this, you need to use dynamic property notation with square brackets:
updatedItem[elem[0]] = elem[1];
This makes a new key with the value of elem[0]
, instead of the key being elem[0]
.
Upvotes: 1