簡體   English   中英

我正在嘗試在我的 MongoDB 數據庫上更新我的帖子,但它顯示:無法讀取 null 的屬性(讀取“updateOne”)

[英]I am trying to update my post on my MongoDB database, but it shows this : Cannot read properties of null (reading 'updateOne')

我正在嘗試更新我在 MongoDB 數據庫上的帖子,但它顯示:無法讀取 null 的屬性(讀取“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;

根據您的問題,您的代碼中有一些錯誤:

  • 在繼續之前始終添加檢查操作是否成功。
  • 使用 Post 而不是 post 來執行操作。(Post Mongoose model 而不是 Post 的實例)
  • 在您的情況下,您可以使用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);
    }
});

作為補充:

  • 實際上需要您注釋的錯誤處理,因為 Express 不會為您處理返回的 promise。(這就是讓您得到UnhandledPromiseRejectionWarning的原因)
  • 您的代碼也不提供對傳入請求的任何形式的驗證,您可能需要考慮先檢查從客戶端接收到的數據,然后再將其插入數據庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM