Dave Kalu
Dave Kalu

Reputation: 1595

Creating mongoose schema that contains array of Objects

How do I create a mongoose schema that has the following structure

 {
       data: {
        name: "John doe",
        attributes: [
          {
            text: "Sample text",
            created_at: "2018-08-23"
         },
        {
            text: "Sample text 2",
            created_at: "2018-08-23"
         }
        ],
       created_at: "2018-08-23"
     }
}

Upvotes: 0

Views: 860

Answers (2)

CyberMessiah
CyberMessiah

Reputation: 1268

This can simply be done with Arrays of Objects instead of creating New Schemas. I don't know if there might be some implications for the optimization.

    attributes: [{
    text: String,
    created_at: Date
}], 

This is following the official Mongoose documentation.

Upvotes: 1

Ashraful Islam
Ashraful Islam

Reputation: 1263

You can try this

const sampleSchema = new mongoose.Schema({
    data: {
        type: dataSchema
    }
});

const dataSchema = new mongoose.Schema({
    name: String,
    attributes: [attributeSchema],
    created_at: Date
});

const attributeSchema = new mongoose.Schema({
    text: String,
    created_at: Date
});

Upvotes: 0

Related Questions