Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

774
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda