【问题标题】:Saving an array property on a Mongoose schema在 Mongoose 模式上保存数组属性
【发布时间】:2012-10-02 01:17:51
【问题描述】:

我有一个类似于以下内容的 mongoose 对象架构:

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

我正在尝试使用以下内容创建新帖子:

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 属性的空数组创建。我做错了什么?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您在新对象中缺少架构的 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();
    

    【讨论】:

      【解决方案2】:

      我刚刚做了类似的事情,在我的情况下附加到现有集合中,请参阅此问题/答案。它可以帮助你:

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

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

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

      【讨论】:

      • 从 v3 开始,您不需要为这些子对象指定模式,您只需将它们指定为父模式中的对象字面量即可。
      猜你喜欢
      • 2017-12-30
      • 1970-01-01
      • 2018-08-15
      • 2014-03-02
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      相关资源
      最近更新 更多