Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategy for sharing and reusing of schema parts in mongoose.js

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.

like image 720
qqilihq Avatar asked Dec 19 '14 17:12

qqilihq


1 Answers

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]
});
like image 64
qqilihq Avatar answered Nov 08 '22 09:11

qqilihq