简体   繁体   中英

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM