在Mongoose模式上保存一个数组属性

我有一个mongoose对象模式,看起来类似于以下内容:

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

我正在尝试使用以下内容创build新post:

 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(); 

但是,一旦我保存post,它创build一个空的数组的图像属性。 我究竟做错了什么?

您在新对象中缺less模式的imagePost对象。 试试这个:

 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(); 

我刚刚做了类似的事情,在我的情况下追加到现有的集合,请看这个问题/答案。 它可以帮助你:

Mongoose / MongoDB – 使用预定义模式附加到文档对象数组的简单示例

你的问题是,在Mongoose中,你不能有嵌套的对象,只能嵌套的模式。 所以你需要做这样的事情(为了你想要的结构):

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