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

261
Vistas
How to push a value to an array field only if it meets a condition in mongoDB?(Nodejs)

I apologize for my poor way of explaining my issue. I am trying to update my schema's notes and assignmentHistory fields. I have no issues updating notes field but with the assignmentHistory field what I am trying to do is append values to the array only if the assingedTo value has changed from it's last value or is not empty only then $push to assignmentHistory array, otherwise don't add anything to assigmentHistory array. Basically, how do I prevent $push not add anything to the assignmentHistory array, not even empty object with _id field? Below is snippet of my code

const RequestSchema = new Schema(
  {
title: { type: String, required: true, max: 32, min: 6 },
priority: { type: String, emum: ["low", "medium", "high"] },
notes: [
      {
        commentNotes: {
          comment: { type: String, max: 200 },
          commentBy: { type: Schema.Types.ObjectId, ref: "User" },
          commentDate: { type: Date },
       }
]
assignedTo: { type: Schema.Types.ObjectId, ref: "User" },
assigmentHistory: [
      {
        techName: { type: Schema.Types.ObjectId, ref: "User" },
        assignedDate: { type: Date },
      }
    ]
}

let noteObj={};
let techobj={};

await RequestModel.findOneAndUpdate(
      { _id },

      {
        $push: {
          notes: [noteObj],
          assignmentHistory:[techobj]
        },
      },
      { new: true }
    );
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In order to only push an element in an array if the value is not present yet, you can use $addToSet. See this example on mongoplayground. Regarding handling the empty object - I'd just do it on the client side and dynamically build the query. So something like:

const addToSetObj = {};
if(!isEmpty(noteObj)) { // use one of the method for isEmpty described here https://stackoverflow.com/q/679915/3761628
  pushObj.notes = noteObj;
}
if(!isEmpty(techObj)) {
  pushObj.assignmentHistory = techObj;
}
await RequestModel.findOneAndUpdate(
      { _id },
      {
        $addToSet: addToSetObj
      },
      { new: true }
    );
about 4 years ago · Juan Pablo Isaza Denunciar

0

I do have a work around but would like a more professional way to avoid adding empty objects to the array field.

Basically, I only wanted to push an object to assigmentHistory array field of my schema if assignedTo variable was true. Good Programming doesn't recommend using same code twice, but in my case I have used the findoneAndUpdate query twice in the if and else condition. Please feel free to optimize it. All I want is when assignedTo variable is false , then $addToSet not add an empty object in the assignmentHistory array field.

if (
  assignedTo &&
  assignedTo.toString() !== oldRequest.assignedTo.toString()
) {
      await RequestModel.findOneAndUpdate(
        { _id },

        {
          $set: requestFields,
          $push: {
            notes: [noteObj],
          },
          $addToSet: { assigmentHistory: [newtech_info_object] },
        },
        { new: true }
      );
    } else {
      await RequestModel.findOneAndUpdate(
        { _id },

        {
          $set: requestFields,
          $push: {
            notes: [noteObj],
          },
        },
        { new: true }
      );
    }
about 4 years ago · Juan Pablo Isaza 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