Saving an array property on a Mongoose schema

后端 未结 2 1547
温柔的废话
温柔的废话 2020-12-29 14:48

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

var postSchema = new Schema({
   imagePost: {
     images: [{
        url: String,
              


        
2条回答
  •  感动是毒
    2020-12-29 15:22

    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]
    });
    

提交回复
热议问题