Skip to content

Mongoose update Sub-Document

How to updating sub-document in mongoose:

this is my JSON DATA

[

{
_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",
},
]
}   
  ]

This is the post Schema.

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

this is the NodeJs part

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

**

I got this response in Postman: post.comments.update is not a function it accept post.update but it’s not what i want because the property message is in the sub-doc of each post object, any help Please


**

Answer

You should run the method Model.update() on the Model “Post” not the instace “post” of it. A similar question is answered here.