I am trying to implement an array of comments as a subdocument, in my main document of posts, I am new to js and mongoose, while I tried updateOne, it is working, but it is not working if I use the save parameter, and if I add another comment, the comment is replacing but not adding as another comment. If I am question is dumb, that is because I am very new, please help me out. image of my document
the codes I tried:
this code works, but as I said, whenever the new comment is made, it is replacing:
//add comment
router.post("/:id/comment", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
const comment = await post.updateOne({ $set: { comments: req.body } });
res.status(200).json(comment);
} catch (err) {
res.status(500).json("error");
}
});
the save parameter:
//add comment
router.post("/:id/comment", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
const comment = await post.save({ $set: { comments: req.body } });
res.status(200).json(comment);
} catch (err) {
res.status(500).json("error");
}
});
my model file:
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema(
{
userId: {
type: String,
require: true,
},
description: {
type: String,
max: 1000,
},
image: {
type: Array,
},
likes: {
type: Array,
default: [],
},
comments: [
new mongoose.Schema(
{
userId: {
type: String,
require: true,
},
comment: {
type: String,
default: "",
},
},
{ timestamps: true }
),
],
},
{ timestamps: true }
);
module.exports = mongoose.model("Post", PostSchema);
You are using wrong update operator. If you want to add an element to an array use $push
operator. This will update the array, whereas $set
will just set the value you are providing, thus overwriting previous values.