I've read all the similar questions in here, and they don't work. I'm trying to update a model called Transaction, and I'm using findOneAndUpdate to update it. There is no errors, but the doc simply returns null. Code:
app.post("/transaction/update", isAdmin, async (req, res) => {
const username = "dennis"
const count = req.body.count
const date = req.body.date
const change = req.body.change
const service = req.body.service
const expires = req.body.expires
const transaction = await Transaction.findOneAndUpdate({ "username": "dennis" }, {
$set: {
"count": count,
"date": date,
"change": change,
"service": service,
"expires": expires
}
}, { new: true }, (err, doc) => {
if (err) {
console.log(err)
}
console.log(doc)
})
await transaction.save()
res.redirect("/admin")
})
Try this instead:
app.post("/transaction/update", isAdmin, async (req, res) => {
const username = "dennis"
const count = req.body.count
const date = req.body.date
const change = req.body.change
const service = req.body.service
const expires = req.body.expires
const transaction = await Transaction.findOneAndUpdate({ "username": "dennis" },
{
"count": count,
"date": date,
"change": change,
"service": service,
"expires": expires,
}, { new: true })
res.redirect("/admin")
})
You don't have to use $set
or call .save()
.
Reference: https://www.freecodecamp.org/news/introduction-to-mongoose-for-mongodb-d2a7aa593c57/#update-record
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.