Saving an array property in Mongoose schema

I have a mongoose object schema that looks something like this:

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

I am 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, as soon as I save the message, it is created with an empty array for the images property. What am I doing wrong?

+7
source share
2 answers

You are missing the imagePost object of your schema in the new object. Try 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(); 
+6
source

I just did something similar, in my case adding to an existing collection, please see this question / answer. This may help you:

Mongoose / MongoDB - a simple example of adding an array of document objects with a predefined schema

Your problem is that in Mongoose you cannot have nested objects, but only nested schemes. 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] }); 
+2
source

All Articles