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

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

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 Denunciar

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 Denunciar

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 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