简体   繁体   中英

How do I make a PUT request with express and Postman in order to change a given MongoDB field?

I want to be able to insert a given MongoDB document's id in the route and use the body in Postman to change eg the 'balance' field of that document, but I can't seem to make it work. My code looks like this so far. My route:

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))
});

My model:

const AccountSchema = new mongoose.Schema({

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

I recommend you to split up the operations(find at first, then update, then save) Try something like this in callback of your put handler:

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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM