npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongoose-sub-references-populate

v1.0.2

Published

Package useful for populating references to sub documents

Downloads

70

Readme

Package: mongoose-sub-references-populate

Package useful for populating references to sub documents. It will add a query builder helper and a model's method helper.

N.B: Using sub references is considered in most of the cases an anti-pattern that you should avoid (usually you can re-organize your data to avoid it).

Install

npm i mongoose-sub-references-populate

Setup

// Including the library will add 'subPopulate' helper for query
const subReferencesPopulate = require('mongoose-sub-references-populate');

const TestSchema = new mongoose.Schema({});

// Applying as plugin on the schema will provide 'subPopulate' method on the model
TestSchema.plugin(subReferencesPopulate);
const TestModel = mongoose.model('Test', TestSchema);

Usage

Defining a sub reference

To an Array of SubDocuments

For example:

const PersonSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  contacts: [
    {
      email: {
        type: String,
      },
    },
  ],
});
const PersonModel = mongoose.model('Person', PersonSchema);

const MessageSchema = new mongoose.Schema({
  contact: {
    type: mongoose.Schema.Types.ObjectId,
    subRef: 'Person.contacts',
  },
  content: {
    type: String,
  },
});
MessageSchema.plugin(subReferencesPopulate);
const MessageModel = mongoose.model('Message', MessageSchema);

The subRef: 'Person.contacts' will do the magic. You can now call the following methods:

    const message = await MessageModel.findById(...);
    message.subPopulate('contact');

    // or
    const subPopulatedResults = await MessageModel.find(..).subPopulate('contact');

The field 'contact' will be populated with the corresponding referenced sub document.

To an Array of References

For example:

const ContactSchema = new mongoose.Schema({
  email: {
    type: String,
  },
});
const ContactModel = mongoose.model('Contact', ContactSchema);

const PersonSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  contacts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Contact' }],
});
const PersonModel = mongoose.model('Person', PersonSchema);

const MessageSchema = new mongoose.Schema({
  contact: {
    type: mongoose.Schema.Types.ObjectId,
    subRef: 'Person.contacts',
  },
  content: {
    type: String,
  },
});

MessageSchema.plugin(subReferencesPopulate);
const MessageModel = mongoose.model('Message', MessageSchema);

You might think it would be better to put a direct reference to the ContactModel instead of Person.contacts. The difference will be: if it doesn't exist a Person with the referenced sub document than contact will not be sub populated even if it has the right _id to an existing Contact. If you sub populate this way, you're sure that a Person has that contact.

Bound to fields

If you want to increase the performance of the queries, it is possibile to use the boundTo schemaType options:

const PersonSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  contacts: [
    {
      email: {
        type: String,
      },
    },
  ],
});
const PersonModel = mongoose.model('Person', PersonSchema);

const MessageSchema = new mongoose.Schema({
  person: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Person',
    required: true,
  },
  contact: {
    type: mongoose.Schema.Types.ObjectId,
    subRef: 'Person.contacts',
    boundTo: 'person',
  },
  content: {
    type: String,
  },
});
MessageSchema.plugin(subReferencesPopulate);
const MessageModel = mongoose.model('Message', MessageSchema);

Storing the root reference of where is the sub document we're interested in.

Nesting paths

Both subRef and boundTo allow any path you want. The most important thing is to remember it must ends with a schema type Array of References or Array of Sub Documents and it must have not arrays in the between path.

Object --- > Object ---> .... any time you want ---> Array

Test

You can try the tests using the following command ( before you need to change the connection to MongoDB ) :

npm install --test
npm run test

See also

If you want to provide an integrity to your sub references, you could be interested in sub-references-integrity

Support

If you would like to support my work, please buy me a coffe ☕. Thanks in advice.