Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

288
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!