我對 nodejs/express 相當陌生,我正在使用 devchallenges.io 練習全堆疊開發,我正在做shoppingify 挑戰。我正在嘗試更新我在 items 陣列中定位的專案的數量。我知道我在下面的嘗試很糟糕,我真的很難理解能夠做到這一點的邏輯。
// @route PUT api/list/item/quantity/:id
// @desc Increase or decrease quantity
// @access Private
router.put('/item/quantity/:id', auth, async (req, res) => {
const { action } = req.body;
try {
let list = await List.findOne({ user: req.user.id });
const item = list.items.find(
(item) => item._id.toString() === req.params.id
);
list = list.updateOne(
{ 'items._id': req.params.id },
{ $set: { 'items.quantity': item.quantity 1 } }
);
await list.save();
return res.json(list);
} catch (error) {
console.error(error.message);
res.status(500).send('Server Error');
}
});
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ListSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
},
name: {
type: String,
default: 'Shopping List',
},
items: [
{
name: {
type: String,
default: '',
},
note: {
type: String,
default: '',
},
image: {
type: String,
default: '',
},
category: {
type: String,
default: '',
},
quantity: {
type: Number,
default: 1,
},
},
],
date: {
type: Date,
default: Date.now,
},
});
module.exports = List = mongoose.model('list', ListSchema);
uj5u.com熱心網友回復:
看,這是我的更新供應商路線,我正在更新嵌套的街道和城市名稱。
router.put("/update-vendors", async (req, res, next) => {
const vendor = await Vendor.updateOne(
{
"address.street": "Street2",
},
{
$set: {
"address.$.street": req.body.street,
"address.$.city": req.body.city,
},
}
);
res.status(200).json(vendor);
});
您可以借助$set其他$push方法更新特定內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/396468.html
上一篇:如何使用聚合確定用戶收集了多少點
