How to updating sub-document in mongoose:
this is my JSON DATA
JavaScript
x
22
22
1
[
2
3
{
4
_id: "60215bb12390573490fb30c4",
5
publishedAt: "2021-02-08T15:41:28.562Z",
6
comments: [
7
{
8
messageAt: "2021-02-08T15:47:04.197Z",
9
_id: "60215d92f16e9f208c8663a1",
10
message: "beautiful picture",
11
userId: "600c26312c1e41372015e834",
12
},
13
{
14
messageAt: "2021-02-09T13:55:49.414Z",
15
_id: "60229495e285843da095f84e",
16
message: "wonderful view",
17
userId: "600c26312c1e41372015e834",
18
},
19
]
20
}
21
]
22
This is the post Schema.
JavaScript
1
26
26
1
const postSchema = new mongoose.Schema({
2
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required:
3
true },
4
photos: [{
5
type: String,
6
required: true
7
}],
8
description: {
9
type: String,
10
required: true
11
},
12
publishedAt: {
13
type: Date,
14
default: new Date()
15
},
16
likes: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
17
comments: [
18
{
19
message: { type: String, required: true },
20
messageAt: { type: Date, default: new Date() },
21
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User',
22
required: true },
23
}
24
]
25
});
26
this is the NodeJs part
JavaScript
1
20
20
1
router.patch('/comment/:postId/:commentId', auth, async (req, res) => {
2
try {
3
const { postId, commentId } = req.params;
4
5
const post = await Post.findById(postId);
6
if (!post) return res.status(400).send('Invalid Post');
7
8
post.comments.update(
9
{ _id: commentId },
10
{
11
$set: { message: req.body.message }
12
}
13
)
14
15
res.send('Comment updated successfully');
16
} catch (error) {
17
res.status(400).send(error.message);
18
}
19
});
20
**
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
**
Advertisement
Answer
You should run the method Model.update() on the Model “Post” not the instace “post” of it. A similar question is answered here.