简体   繁体   中英

Mongoose schema for storing an array of JSON objects for subdocuments

I have a JSON object that I want to create a schema for using mongoose

    { ProjectName: 'asdf',
  Embargo: 'Yes',
  Angle: '1',
  Facts: '[{"count":1,"fact":"dsafdsaf","content":"dsafdsaf"}, {"count":3,"fact":"dsafdsaf","content":"dsafdsaf" } , {"count":2,"fact":"dsafdsaf","content":"dsafdsaf"}]',
  About: '<p>Anthony Bodin&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>',
  EditorNote: 'No',
  OrderId: 'tok_14kGRO2Jju1nvjb47YF9jQTJ',
  Payment: 'Paid' }

My problem is that the Facts element will contain and array of objects and I am not quite sure how to save it into the database as Here is the schema that I have right now

var ArticleSchema = new mongoose.Schema({
    userId: {
        type: String,
        default: ''
    },
    userEmail: {
        type: String,
        default: ''
    },
    article: {
        date: {
            type: Date,
            default: Date()
        },
        ProjectName: {
            type: String,
            default: ''
        },
        Embargo: {
            type: String,
            default: true
        },
        Angle: {
            type: String,
            default: ''
        },
        Facts: {                
            type:Array
        },
        About: {
            type:String,
            default:''
        },
        EditorNote: {
            type:String,
            default:''
        },  
        Payment: {
            type: String,
            default: 'Not Paid'
        },
        OrderId: {
            type:String,
            default:''
        }
    }
});

Is saving the data as an array the right way to save the Facts element ?

Its very simple. Just make facts an array. So change

Facts: {                
            type:Array
        },

to Facts: [] and it will be able to store the array of objects you have there in the Facts json field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM