router.put("/goods/:goodsId/cart", async (req, res) => {
const {
params: { goodsId },
body: { quantity },
} = req;
const existsCart = await Cart.find({ goodsId: Number(goodsId) });
if (existsCart.length) {
await Cart.updateOne({ goodsId: Number(goodsId) }, { $set: { quantity } });
}
res.json({ success: true });
});
put 메서드로 mongo db 데이터를 업데이트 하는 코드를 공부하는데 $set 이라는 기호를 보았다. Mongo DB 공식문서를 살펴보니
The[$set]operator replaces the value of a field with the specified value.
이렇게 되어있다.
필드의 value를 특정 value로 변환시키는 명령어로 보인다.
{ $set: { <field1>: <value1>, ... } }
위와 같이 사용을 한다.
await Cart.updateOne({ goodsId: Number(goodsId) }, { $set: { quantity } });
위 코드에서 보면, field가 quantity로 특정되어 있는 것을 알 수 있다.
키, 값이 동일하므로 quantity 하나만 쓴 것을 알 수 있다.(es6 문법(property shorthand)을 사용해 )
Mongo DB 공식문서의 예제를 보면 더 쉽게 이해가 간다.
db.products.insertOne(
{
_id: 100,
quantity: 250,
instock: true,
reorder: false,
details: { model: "14QQ", make: "Clothes Corp" },
tags: [ "apparel", "clothing" ],
ratings: [ { by: "Customer007", rating: 4 } ]
}
)
👇
db.products.updateOne(
{ _id: 100 },
{ $set:
{
quantity: 500,
details: { model: "2600", make: "Fashionaires" },
tags: [ "coats", "outerwear", "clothing" ]
}
}
)