Reputation: 993
This is the Mongoose Schema:
var userschema = new mongoose.Schema({
user: String,
imagen: [{
tags: [String],
}]
});
I'm getting the tags with this:
var bodytags = req.body.tags;
var tags = tbags.split(" ");
I get the tags from req.body, and put all of them within an array. But the problems comes here:
var img = usermodel.findOne({ user: req.session.user }, function(err, user){
var img = user.imagen.push({
tags: undefined
});
});
img.tags.push(tags);
And when, I received an error that sais TypeError: Cannot call method 'push' of undefined
. How can I push my array of tags inside the tags' array of my Schema?
Thank's advance!
EDITED:
And this would be the result of what I want:
{
user: randomuser,
imagen: [{
tags: ["one", "two", "three"
}]
}
And, if for example, there are two imagen objects:
{
user: randomuser,
imagen: [{
tags: ["one", "two", "three"]
},
{
tags: ["four", "five", "six"]
}]
}
Upvotes: 1
Views: 2494
Reputation: 6712
Seems the error could be due to inconsistencies in variable assignment. So have created a stand-alone example to test and it works
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/images');
var UserSchema = new mongoose.Schema({
user: String,
imagen: [ {
tags: [String]
} ]
});
var User = mongoose.model('User', UserSchema);
var newUser = new User({ user: 'Almypal'});
var bodytags = 'Home basic tutor';
var tagarray = bodytags.split(" ");
newUser.save(function(err, result){
if(err)
{
console.log(JSON.stringify(err));
}
else
{
result.imagen.push({ tags: tagarray });
result.save( function(error, data){
if(error){
console.log(JSON.stringify(error));
}
else{
console.log(JSON.stringify(data));
}
});
}
});
MongoDB now has the following document
{ "_id" : ObjectId("50e84425862a2af616000001"), "imagen" : [ { "tags" : [ "Home", "basic", "tutor" ] } ], "user" : "Almypal" }
Hope this helps.
Upvotes: 1