1

Suppose I have the following schema:

const personSchema = mongoose.Schema({
    firstname: String,
    lastname: String,
    email: String,
    gender: {type: String, enum: ["Male", "Female"]}
    dob: Date,
    city: String,
    interests: [interestsSchema],
    // vs this
    // interests: [{type: Schema.Types.ObjectId(), ref: 'Interest'}]
});

What are the difference between the two methods here? What are the advantages and disadvantages of one vs the other?

1 Answer 1

1

There is obviously no perfect answer to this question, it all depends on the scenario, where and how will you use the data.

ObjectId vs Embedded

I use both embedded documents and lists of ObjectIds. For example, I have two collections, Customers and Contacts. Every Customer can have multiple contacts, and multiple Customers should be able to use the same contact. We also want to list and manage contacts separately.

We also have an array of addresses, which is unique to each Customer document, we do not need to list or manage them separately or reuse them ever again, so it makes sense to embed them.

Customer

{
  businessName: string,
  contacts: [ObjectId, ObjectId],
  address: {
    invoice: [{
      street: string
      zip: string
      city: string
    }]
  }
}

Contact

{
  firstName: string
  lastName: string
  phoneNumber: string
  email: string
}

Array size

This is just a side note, not relevant to the question, just some more information about arrays in MongoDB.

What you are describing here is a so called one-to-many relationship, where one document may have any number of embedded documents.

MongoDB works best with "one-to-few" when using any type of array, they usually recommend you to not have an array containing more than a hundred documents, if there are more, it will start to impact query times in one way or another.

The same goes for the ObjectId array, it should not be more than a hundred in the array.

If you expect the array to increase beyond a hundred, you should use a separate collection with a property like personId where every interest refers to the person. This way, you don't need the array at all in the personSchema.

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

2 Comments

Suppose I want to delete an interest by id from my query, does that update in the interests array in Person? Is it possible to have this set up automatically?
@redstuck I haven't worked with mongoose for quite a while, but back when I did, I had to build my own logic for this. You can create a pre function that handles any referencing data from other collections before saving.

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.