Hello,
If we consider the following document that contains 1 embedded document:
{
"product": {
"type": "Dairy"
},
"weight": 2,
"quantity": 1
}
In order to update the product’s type one could do the following:
{"product.type" : "Vegetable"}
However, let’s suppose we wanted to update the document dynamically, as many both embedded and non-embedded values as we prefer.
Ergo, an idea would be to build a query object:
const updateQuery = {
"product": {
"type": "Vegetable" //modify this
},
"weight": 3 //modify this too
}
and pass it as a parameter to the updateProductById()
function:
const updateProductById = async(productId: string, updateQuery) => {
await ProductsModel.findOneAndUpdate(
{_id: productId},
{$set: updateQuery},
{new: true}
).exec()
However, this will overwrite the original embedded document, resulting in a regenerated embedded document’s _id
key.
Thus, we would have to do the following instead:
const updatedProduct = await ProductsModel.findOneAndUpdate(
{ _id: productId },
{ "product.type": "Vegetable" },
{ new: true }
).exec()
That’s good for that one value only, but
-
how do you use
{"product.type" : "Vegetable"}
dynamically in Javascript passed along with other, non-embedded values? -
Is it possible to somehow express this key- value pair in a Javascript object?
-
finally, could you tell me please, how to describe this in a Typescript interface?
Thank you!