mongoose 当我尝试更新mongodb文档时,状态代码为500

dced5bon  于 2023-10-19  发布在  Go
关注(0)|答案(1)|浏览(136)

我得到一个服务器端错误:[AxiosError:请求失败,状态代码为500。很明显我的请求有问题,但不确定是什么。
此react-native应用程序的控制台错误指向updateError函数:费用-上下文.js:76:6
调用堆栈
x1c 0d1x这是数据在组件之间移动的方式:
ExpenseForm.js是构造expenseData的地方:

async function submitHandler() {
        const expenseData = {
            amount: +inputs.amount.value,
            date: new Date(inputs.date.value),
            description: inputs.description.value,
            _id: inputs._id.value
        }

之后,expenseData被传递给确认器:

function confirmHandler(expenseData) {
        if (isEditing) {
            expensesCtx.updateExpense(_id, expenseData)
            console.log('expenseData', expenseData)
            navigation.goBack()
        } else {
            expensesCtx.addExpense(expenseData)
            navigation.goBack()
        }

控制台日志expensieData的输出如下:

expenseData {"_id": "64e1aaad97da840a04ce64e5", "amount": 99.99, "date": 2023-08-19T00:00:00.000Z, "description": "Update Expense"}

然后,expenses-context.js中的updateData获取_id和expenseData:

async function updateExpense(_id, expenseData) {
            try {
                await axios.put(`http://localhost:8082/expenses2/${_id}`, expenseData);
                dispatch({ type: 'UPDATE', payload: { _id: _id, data: expenseData } });
            } catch (error) {
                console.error('Error updating expense:', error);
            }
        }

最后,app.put在server.js中被调用,并传递了_id和expenseData:

await Expense.findByIdAndUpdate({ _id: ObjectId(_id) }, { $set: expenseData });

在上面的行中

app.put("/expenses2/:_id", async (req, res) => {
            const _id = req.params._id;

            try {
                // Update the expense in the database based on expenseId and req.body
                const expenseData = req.body
                await Expense.updateOne({ _id: ObjectId(_id) }, { $set: { expenseData } });

                res.json({ message: 'Expense updated successfully' });
            } catch (error) {
                console.error('Error updating expense:', error);
                res.status(500).json({ error: 'An error occurred while updating the expense' });
            }
        });
ac1kyiln

ac1kyiln1#

这可能是因为您在路由处理程序的updateOne方法中使用$set操作符的方式。您正在将整个expenseData对象设置为文档中的字段。相反,您应该直接将expenseData对象传递给$set。

app.put("/expenses2/:_id", async (req, res) => {
    const _id = req.params._id;

    try {
        // Update the expense in the database based on expenseId and req.body
        .....

        // Use the _id to update the specific expense
        await Expense.updateOne({ _id: ObjectId(_id) }, { $set: expenseData });

        res.json({ message: 'Expense updated successfully' });
    } catch (error) {
       //... handle error
    }
})

相关问题