Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

772
Views
How to insert data in nested arrays mongodb?

This is my post model that is stored in mongodb.

const PostSchema = new mongoose.Schema({
  text: {
    type: String,
    required: "Name is required",
  },

  photo: {
    data: Buffer,
    contentType: String,
  },
  likes: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
  comments: [
    {
      text: String,
      created: { type: Date, default: Date.now },
      postedBy: { type: mongoose.Schema.ObjectId, ref: "User" },
      likes: Number,
      incomments:[{text:String,postedBy:{ type: mongoose.Schema.ObjectId, ref: "User" }}]
    },
  ],
  postedBy: { type: mongoose.Schema.ObjectId, ref: "User" },

I want to insert comments inside comments array i.e insert comments in incomments array inside comments array.

const commentincomment=(req,res)=>{
  Post.findOneAndUpdate(
    {"_id":req.body.postId,
    "comments.text":req.body.comment,
    "comments.postedBy":req.body.postedBy
    },
    {$push:{"comments.$.incomments":{
      text:req.body.comtext,
      postedBy:req.body.userId
    }}}).exec((err, result) => {
      if (err) {
        return res.status(400).json({
          error: err,
        });
      }
      res.json(result);
    });
  
}

I am doing this but the array is not updating. Any suggestions?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You need to typecast variables postId and postedBy containing string value to ObjectId. Try this:

const mongoose = require('mongoose');

const commentincomment = (req, res) => {
  let conditions = {
    "_id": mongoose.Types.ObjectId(req.body.postId),
    "comments.text": req.body.comment,
    "comments.postedBy": mongoose.Types.ObjectId(req.body.postedBy)
  };

  let postDoc = {
    $push: {
      "comments.$.incomments": {
        text: req.body.comtext,
        postedBy: req.body.userId    // Also typecast this if required.
      }
    }
  }

  let options = {
    new: true
  };

  Post
    .findOneAndUpdate(conditions, postDoc, options)
    .exec((err, result) => {
      if (err) {
        return res.status(400).json({
          error: err,
        });
      }
      res.json(result);
    });
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!