Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda