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?
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);
});
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.
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);
});