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!
There is no such item in any array: anyArray[anyArray.length].
You must use anyArray[anyArray.length - 1] i think.
It's undefined because you've gone off the end of the user.imagen array. It only has user.imagen.length elements so with JavaScript's 0-based array indexes the last element is at index user.imagen.length-1.
If you're trying to add a new element:
usermodel.findOne({ user: req.session.user }, function(err, user){
user.imagen.push({ title: req.body.title });
user.save(function(err){
if(err) { throw err; }
});
});