Aakash
Aakash

Reputation: 167

how to update subdocument in mongoose?

my schema look like this:

{
"blogTitle":"Book"
"blogContent":"demo"
"blogrelatedLink":{
    "relatedBloogId:"123",
    "relatedBlogTitle":"abc"`
    }
}

and my code is:

const updateBlogs = async (req, res) => {
    const { blogId } = req.params;
    const re = /<("[^"]?"|'[^']?'|[^'">])*>/;

    if (re.test(req.params.blogTitle)) {
        sendError(400, "Unsuccessful", "Blog Title cannot be HTML", req, res);
    } else {
        try {
            let update = {};
            if (req.body.blogTitle) update.blogTitle = req.body.blogTitle;
            if (req.body.blogContent) update.blogContent = req.body.blogContent;
            let blog = await Blog.updateOne(
                { blogId },
                {
                    $set: update,
                },
                { runValidators: true }
            );
            sendResponse(200, "Successfull", blog, req, res);
        } catch (err) {
            sendError(400, "Blog can't be updated by given id", err, req, res);
        }
    }
};

what will be the code to update subdocument

Upvotes: 0

Views: 160

Answers (1)

turivishal
turivishal

Reputation: 36104

The update key should be in this <main key name>.<sub key name>: <value to be update> format, just put this before your update query,

if (req.body.blogrelatedLink) {
  for (let key in req.body.blogrelatedLink) {
    update['blogrelatedLink.' + key] = req.body.blogrelatedLink[key];
  }
}

Playground

Upvotes: 1

Related Questions