在Mongoose模式上保存数组属性 [英] Saving an array property on a Mongoose schema

查看:120
本文介绍了在Mongoose模式上保存数组属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个猫鼬对象架构,看起来类似于以下内容:

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

但是,一旦我保存了帖子,就会使用images属性的空数组来创建帖子.我在做什么错了?

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

推荐答案

在新对象中缺少架构的imagePost对象.尝试以下方法:

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

这篇关于在Mongoose模式上保存数组属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆