Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

319
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda