![](/img/trans.png)
[英]my database does not Update when I run my code using update or updateOne
[英]I am trying to update my post on my MongoDB database, but it shows this : Cannot read properties of null (reading 'updateOne')
const router = require("express").Router();
const Post = require("../moduls/Post");
router.post("/", async (req, res) => {
const newpost = Post(req.body);
try {
const savedPost = await newpost.save();
res.status(200).json(savedPost);
} catch (error) {
res.status(500).json(error)
}
});
在這里,我嘗試編寫代碼來更新我的帖子。 但它不起作用。
//Update Post
router.put("/:id", async (req, res) => {
// try {
const post = await Post.findById(req.params.id);
if (post.userId === req.body.userId) {
await post.updateOne({ $set: req.body })
}
else {
res.status(403).json("You can't update it")
}
// } catch (error) {
// res.status(500).json("Internal Error")
// }
})
module.exports = router;
根據您的問題,您的代碼中有一些錯誤:
findOneAndUpdate
無需先找到相應的 Post 然后再更新。router.put("/:id", async (req, res) => {
try {
const postUpdated = await Post.findOneAndUpdate(
{
_id: mongoose.Types.ObjectId(req.params.id),
userId: mongoose.Types.ObjectId(req.body.userId) // assuming it is saved as a mongo id
},
req.body,
{ new: true }
);
if (!postUpdated) {
throw new Error('could not update Post');
}
res.json(postUpdated);
} catch (e) {
res.sendStatus(500);
}
});
作為補充:
UnhandledPromiseRejectionWarning
的原因)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.