1

I'm defining my schema in mongoose and I have an array of book objects, and then an "active book". Now setting it up wasn't an issue, but this seems like unnecessary repetition to define the exact same book object in two different parts of the schema.

 var BookSchema   = new Schema({
    activeBook: {
        id: String,
        title: String,
        author: String,
        pages: Number
    },
    books: [{
        id: String,
        title: String,
        author: String,
        pages: Number
    }]
});

Is there a cleaner way of writing this so I don't have to write out the same object everywhere I use it?

1 Answer 1

1

A cleaner way would be to create a subdocument, a document with a schema of its own which are elements of a parent's document array. So in your example above you can define the child/parent schema as follows:

var ChildSchema = new Schema({
    id: String,
    title: String,
    author: String,
    pages: Number
});

var ParentSchema = new Schema({
    activeBook: ChildSchema,
    books: [ChildSchema]
});
Sign up to request clarification or add additional context in comments.

Comments

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.