简体   繁体   中英

Write an array inside another array in a Mongoose Schema

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"]

              }] 

 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM