Mongodb – advice on modeling schema to have better access to foreign entity

mongodb

I am fairly new to modeling on MongoDB–please consider this simple example schema

const userSchema = Schema({
  name: String,
  username: String
});

const addressSchema = Schema({
    user: { type: Schema.Types.ObjectId, ref: 'User' },
    street: Schema.Types.String,
    city: Schema.Types.String,
    state: Schema.Types.String,
    zip: Schema.Types.String,
});

Since querying addresses by user will be a constant job, what is the right choice to make?

a) place an "addresses" field in User schema as

addresses: [{ type: Schema.Types.ObjectId, ref: 'User' }]

b) having a virtual property on User

userSchema.virtual('addresses', {
  ref: 'Address',
  localField: '_id',
  foreignField: 'user'
});

Is this a good use of virtual type, according to mongoose docs?

are document properties that you can get and set but that do not get
persisted to MongoDB. The getters are useful for formatting or
combining fields, while setters are useful for de-composing a single
value into multiple values for storage

It doesn't quite fall in the situation they describe, so I'm not sure if it applies.

Best Answer

The following schema may be better to match your requirement.

{
    name: String,
    username: String,
    address: {
        street: String,
        city: String,
        state: String,
        zip: String,
    }
}

Try to avoid having multiple collections like a relational database. Joining is a costly operation in NoSQL databases.

References:

6 Rules of Thumb for MongoDB Schema Design: Part 1

6 Rules of Thumb for MongoDB Schema Design: Part 2

6 Rules of Thumb for MongoDB Schema Design: Part 3

Related Question