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

289
Visualizações
Cannot read property 'push' of undefined

Here's my mongoose schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CartSchema = new Schema({
 userID: String,
 items: [{
   itemID: String,
   quantity: Number
 }]
});

module.exports = mongoose.model('Cart', CartSchema);

Here's the node.js server which uses Express. It has /add-to-cart route which if triggered it should update user's cart with the information passed in req.body:

router.post('/add-to-cart', function(req, res, next) {
      Cart.find({ userID: req.body.userID }).then(function(userCart){
          console.log("TEST: "+JSON.stringify(userCart));
          var myItem = {itemID: req.body.itemId, quantity: 1}
          userCart.items.push(myItem);
          res.send(userCart);
       }).catch(next);
    });

I printed to terminal userCart as you can see in my code and it returned me this:

[{
  "_id":"58f7368b42987d4a46314421",  // cart id
  "userID":"58f7368a42987d4a46314420", // userid
  "__v":0,
  "items":[]   
}]

When the server executes userCart.items.push(myItem); it returns this error:

Cannot read property 'push' of undefined

Why items is not defined if I've already defined its structure in mongoose?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

As adeneo correctly pointed out, userCart is clearly an array but you need to use one of the update methods to push the document to the items array, would suggest Model.findOneAndUpdate() as in

router.post('/add-to-cart', function(req, res, next) {
    Cart.findOneAndUpdate(
        { userID: req.body.userID },
        { $push: { items: { itemID: req.body.itemId, quantity: 1 } } },
        { new: true }
    )
    .exec()
    .then(function(userCart) {
        console.log("TEST: "+ JSON.stringify(userCart));
        res.send(userCart);
    })
    .catch(next);
});
about 4 years ago · Santiago Trujillo Relatório

0

As adeneo pointed out userCart is an array since you are you are using the find method. But clearly you need to find just one document given by its userID so it advised to use findOne() instead.

Also you will need to save the document in order for the changes to actually reflect.

Have a look at the updated code below:

router.post('/add-to-cart', function(req, res, next) {
  Cart.findOne({ userId: req.body.userID }, function(err, userCart){
      if(err) return next(err);
      console.log("TEST: "+JSON.stringify(userCart));
      var myItem = {itemID: req.body.itemId, quantity: 1}
      userCart.items.push(myItem);
      userCart.save(function(err, usersCart) {
           if(err) return next(err);
           res.send(usersCart);
      })
   })
});

Hope this helped.

about 4 years ago · Santiago Trujillo Relatório

0

This can be solved using:

router.post('/add-to-cart', function(req, res, next) {
  Cart.findOne({ userID: req.body.userID }).then(function(userCart){
      console.log("TEST: "+JSON.stringify(userCart));
      const a = req.body.items;
      for(i=0;i<a.length;i++)
      {
        userCart.items.push(req.body.items[i]);
      }
      res.send(userCart);
   }).catch(next);
});
about 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