This is my schema:
var userschema = new mongoose.Schema({
user: String,
imagen: [{
title: String,
name: String,
path: String,
}]
});
And I’m trying this:
usermodel.findOne({ user: req.session.user }, function(err, user){
var img = user.imagen[user.imagen.length];
img.title = req.body.title;
user.save(function(err){
if(err) { throw err; }
});
});
An the console returns TypeError: Cannot set property 'title' of undefined. So, I don’t know why is undefined. I think I have to create a new array element, and then set the properties of that array element, but I don’t no how. Any solution to this…?
Thank’s advance!
It’s undefined because you’ve gone off the end of the
user.imagenarray. It only hasuser.imagen.lengthelements so with JavaScript’s 0-based array indexes the last element is at indexuser.imagen.length-1.If you’re trying to add a new element: