【发布时间】:2022-01-26 02:09:14
【问题描述】:
我是 nodejs/express 的新手,我正在使用 devchallenges.io 练习全栈开发,我正在做购物挑战。我正在尝试更新我在 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);
【问题讨论】:
标签: node.js mongodb express mongoose