簡體   English   中英

Mongoose 更新子文檔

[英]Mongoose update Sub-Document

如何更新 mongoose 中的子文檔:

這是我的 JSON 數據

[

{
_id: "60215bb12390573490fb30c4",
publishedAt: "2021-02-08T15:41:28.562Z",
comments: [
{
messageAt: "2021-02-08T15:47:04.197Z",
_id: "60215d92f16e9f208c8663a1",
message: "beautiful picture",
userId: "600c26312c1e41372015e834",
},
{
messageAt: "2021-02-09T13:55:49.414Z",
_id: "60229495e285843da095f84e",
message: "wonderful view",
userId: "600c26312c1e41372015e834",
},
]
}   
  ]

這是帖子架構。

const postSchema = new mongoose.Schema({
    userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: 
  true },
    photos: [{
        type: String,
        required: true
    }],
    description: {
        type: String,
        required: true
    },
    publishedAt: {
        type: Date,
        default: new Date()
    },
    likes: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
    comments: [
        {
            message: { type: String, required: true },
            messageAt: { type: Date, default: new Date() },
            userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', 
required: true },
        }
    ]
});

這是 NodeJs 的一部分

router.patch('/comment/:postId/:commentId', auth, async (req, res) => {
    try {
        const { postId, commentId } = req.params;

        const post = await Post.findById(postId);
        if (!post) return res.status(400).send('Invalid Post');

        post.comments.update(
            { _id: commentId },
            {
                $set: { message: req.body.message }
            }
        )

        res.send('Comment updated successfully');
    } catch (error) {
        res.status(400).send(error.message);
    }
});

**

我在 Postman 中得到了這個回復: post.comments.update 不是 function 它接受 post.update 但這不是我想要的,因為屬性消息在每個帖子的子文檔中 ZA8CFDE6331BD59EB66AC96F8911


**

您應該在 Model“發布”而不是它的實例“發布”上運行方法Model.update() 這里回答了一個類似的問題。

暫無
暫無

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

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