Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
How to best reference another schema in a Mongoose schema property?

I am defining a mongoose User schema.
It will contain a reference to an Address schema:

const AddressSchema = mongoose.Schema({
  street: String,
  city: String,
  zip: String,
});

const UserSchema = mongoose.Schema({
   ...
});

I see from the docs I can do both:

const UserSchema = mongoose.Schema({
  name: String,
  address: {
    type: AddressSchema,
  },
  ...
});

or

const Address = mongoose.model("Address", AddressSchema);

const UserSchema = mongoose.Schema({
  name: String,
  address: {
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Address"
    }
  },
  ...
});

I suppose the only difference is that when querying a User document in the first case I always get address populated, while in the second one I will have to populate() it...

I'm asking just to be sure this is the difference, and if there are subtler ones I should take care of... From the docs I couldn't tell...

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

It really depends on the type of queries you'll need.

If you only need the inner ones in connection to the outer, like the user's private account actions that are supposed to be shown only to him - the subdocument wat is a better way since it doesn't need to populate.

If you will need to show a list of all actions together it'll be a pain to loop over each user to get their actions, then sum it up, and then you'll have that array, so the better way here is what in SQL called "normalization", you'll end up with one collection of all users so you will be able to display it, but each action will have a reference to the user so you can filter it by the specific user

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!