Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating array of objects inside an object mongodb node

I have a mongoDb model defined as follows:-

var mongoose = require("mongoose");

const postModel = new mongoose.Schema({
    postId: {
        type: String,
        unique: true,
        required: true
    },
    authorId: {
        type: String,
        required: true
    },
    post: {
        authorHandle: {
            type: String,
            required: true
        },
        heading: {
            type: String,
            required: true
        },
        message: {
            type: String,
            required: true
        },
        creationDate: {
            type: Date,
            required: true
        },
        image: { type: Array }, 
        video: { type: Array },
        comments: {
            type: Array
        }
    }
});

module.exports = mongoose.model("postModel", postModel);

Now I have a sample value of a document of the above model, suppose:-

postId: "aaa",
authorId: "bbb",
post: {
  authorHandle: "someone#123",
  heading: "hello",
  message: "post 1",
  creationDate: "some creation date string(please ignore this is irrelevant to my question)",
  image: [],
  video: [],
  comments: [
   { commentId: "1", message: "Something", createdAt: sometime },
   { commentId: "2", message: "Something else", createdAt: sometime2 },
   { commentId: "3", message: "Something other", createdAt: sometime3 },
  ]
}

Now say the user wants to update the comment with commentId 2 of this post with postId "aaa". My question is that what is the best way to use the findOneAndUpdate() method to solve this problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const PostModel = require("./models/PostModel"); //just importing the model that is defined above
//the below is happening inside a request handler in Node + Express
PostModel.findOneAndUpdate(
  //what to do here
)

What I have tried is pulling out that whole object and replacing it with a new object with the new message. But that doesnt seem like a very efficient way. Any and all help is greatly appreciated!

>Solution :

You should write:

const updatedPost = await PostModel.findOneAndUpdate(
  { postId: 'aaa', 'post.comments.commentId': 2 },
  { 'post.comments.$.message': 'Updated message'},
  { new: true }
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading