Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an array property on a Mongoose schema

I have a mongoose object schema that looks similar to the following:

var postSchema = new Schema({
   imagePost: {
     images: [{
        url: String,
        text: String
     }]
 });

I'm trying to create a new post using the following:

var new_post = new Post();
new_post.images = [];
for (var i in req.body.post_content.images) {
  var image = req.body.post_content.images[i];
  var imageObj = { url: image['url'], text: image['text'] };
  new_post.images.push(imageObj);
}
new_post.save();

However, once I save the post, it's created with an empty array for the images property. What am I doing wrong?

like image 321
James Avatar asked Oct 01 '12 15:10

James


2 Answers

I've just done something similar, in my case appending to an existing collection, please see this question/answer. It may help you:

Mongoose / MongoDB - Simple example of appending to a document object array, with a pre-defined schema

Your problem is that in Mongoose you can't have nested objects, only nested Schemas. So you need to do something like this (for your desired structure):

var imageSchema = new Schema({
    url: {type:String},
    text: {type:String}
});

var imagesSchema = new Schema({
    images : [imageSchema]
});

var postSchema = new Schema({
    imagePost: [imagesSchema]
});
like image 33
StuR Avatar answered Nov 15 '22 05:11

StuR


You're missing the imagePost object of your schema in your new object. Try this instead:

var new_post = new Post();
new_post.imagePost = { images: [] };
for (var i in req.body.post_content.images) {
  var image = req.body.post_content.images[i];
  var imageObj = { url: image['url'], text: image['text'] };
  new_post.imagePost.images.push(imageObj);
}
new_post.save();
like image 100
JohnnyHK Avatar answered Nov 15 '22 05:11

JohnnyHK