0

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"
     }
}

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

Tried that but the created_at doesn't reflect
Change type as per your requirements. You can use Date.now()
As per the Mongoose docs, mongoose has a timestamps property that automatically generates timestamps mongoosejs.com/docs/guide.html#timestamps. My issue is that the timestamp gets applied to the main object but not to the array of objects.
I missed a property in dataSchema . I have updated the snippet. Try the snippet now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.