【问题标题】:How do I make a PUT request with express and Postman in order to change a given MongoDB field?如何使用 express 和 Postman 发出 PUT 请求以更改给定的 MongoDB 字段?
【发布时间】:2021-02-14 05:39:06
【问题描述】:

我希望能够在路由中插入给定的 MongoDB 文档的 ID,并使用 Postman 中的正文来更改例如该文档的“余额”字段,但我似乎无法使其工作。到目前为止,我的代码看起来像这样。 我的路线:

router.put('/:id', async (req, res) => {
const id = Account.findById(req.params.id);
const updatedAccount = await Account.findByIdAndUpdate(id,{
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    balance: req.body.balance
});
res.end(JSON.stringify(updatedAccount))
});

我的模特:

const AccountSchema = new mongoose.Schema({

firstName: {
    type: String,
    required: true,
},
lastName: {
    type: String,
    required: true,
},
balance: {
    type: String,
    required: true
}
}, { collection: 'account'});

【问题讨论】:

  • 澄清您的问题,添加您的帐户模型,共享堆栈跟踪。

标签: javascript mongodb express postman


【解决方案1】:

我建议您拆分操作(先查找,然后更新,然后保存) 在你的 put 处理程序的回调中尝试这样的事情:

const updates = Object.keys(req.body)
try {
        const account = await Account.findById(req.params.id)
    
        updates.forEach((update) => account[update] = req.body[update])
        await account.save()
    
        if (!account) {
            return res.status(404).send()
        }
    
        res.send(account)
    } catch (e) {
        res.status(400).send(e)
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-21
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多