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

324
Vistas
Mongo DB $push object wraps it in an array first

When I use $push in mongodb, the expected outcome turns out differently. It actually wraps the object I want to push in an array. This is problematic because I'd have to map over the result just to extract it. Any help would be greatly appreciated.

My Mongo Query

const pushAction = {
    $push: {
      cart: {
        id: itemId,
        quantity: quantity
      }
    }
  }

  // Add item to user's cart
  User.update({_id: userId}, pushAction, (err, success) => {
    if (err) {
      res.status(422).json({'error': 'There was a problem adding the item to your cart.'});
    }
    if (success) {
      // Find user and return the cart
      User.findOne({_id: userId}, {cart: 1}, (err, user) => {
        res.status(200).json({'message': 'The item was successfully added to your cart.', cart: user.cart});
      })
    }
  });

User Schema

// Define User Model
const userSchema = new Schema({
  firstName: {
    type: Schema.Types.String,
    required: true
  },
  lastName: {
    type: Schema.Types.String,
    required: true
  },
  password: {
    type: Schema.Types.String,
    required: true
  },
  email: {
    type: Schema.Types.String,
    required: true
  },
  cart: {
    type: Schema.Types.Array
  },
  dateCreated: {
    type: Schema.Types.Date,
    default: Date.now,
    required: true
  },
  dateUpdated: [
    {
      date: {
        type: Schema.Types.Date
      },
      details: {
        type: Schema.Types.ObjectId
      }
    }
  ],
  verified: {
    type: Schema.Types.Boolean,
    required: true
  },
  role: {
    type: Schema.Types.String,
    default: ROLES_BASIC_USER
  }
});

Expected Outcome

"cart" : [ 
    {
        "id" : "587b6b69799ad7ff650edbb5",
        "quantity" : 1
    }, 
    {
        "id" : "587b6b69799ad7ff650edbb5",
        "quantity" : 1
    }, 
    {
        "id" : "587b6b69799ad7ff650edbb5",
        "quantity" : 1
    }
],

Actual Result

"cart" : [ 
        [ 
            {
                "id" : "587b6b69799ad7ff650edbb5",
                "quantity" : 1
            }
        ], 
        [ 
            {
                "id" : "587b6b69799ad7ff650edbb5",
                "quantity" : 1
            }
        ], 
        [ 
            {
                "id" : "587b6b69799ad7ff650edbb5",
                "quantity" : 1
            }
        ]
    ]
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

// Define User Model
const userSchema = new Schema({
  firstName: {
    type: Schema.Types.String,
    required: true
  },
  lastName: {
    type: Schema.Types.String,
    required: true
  },
  password: {
    type: Schema.Types.String,
    required: true
  },
  email: {
    type: Schema.Types.String,
    required: true
  },
  cart:[ {
    id: Schema.Types.ObjectId,
    quantity: Number 
  }],
  dateCreated: {
    type: Schema.Types.Date,
    default: Date.now,
    required: true
  },
  dateUpdated: [
    {
      date: {
        type: Schema.Types.Date
      },
      details: {
        type: Schema.Types.ObjectId
      }
    }
  ],
  verified: {
    type: Schema.Types.Boolean,
    required: true
  },
  role: {
    type: Schema.Types.String,
    default: ROLES_BASIC_USER
  }
});
over 4 years ago · Santiago Trujillo Denunciar

0

Try changing pushAction as follows:

const pushAction = {
    $push: {
        cart: { $each: [ {id: itemId, quantity: quantity } ] }
    }
}

Clean existing items in cart field before trying this. If it still fails then the issue might be with the schema.

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