Suppose, I have two schemas, e.g. for person
and company
. Both of them should have an address
, which consists of a street name
, number
, zip
and city
.
What would be the strategy to avoid copying the address
properties between the two schema definitions? I read about sub docs, but they seem to be (1) tied to exactly one parent schema, (2) always occur in an array.
Almost too obvious, but this is what I came up with finally:
Define the reusable portions separately, however, contrary to my first thoughts: do not use a Schema
here:
var addressSubschema = {
street: String, number: String, zip: String, city: String
}
Simply include this part in actual schemas:
var personSchema = new mongoose.Schema({
name: { type: String, required: true },
title: { type: String },
address: addressSubschema
});
var companySchema = new mongoose.Schema({
name: { type: String, required: true },
addresses: [addressSubschema]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With