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

mongo-join-query

v1.0.2

Published

Joins in mongo

Downloads

400

Readme

mongo-join-query

Travis-CI

Allows you to query your database using linked collections in your query.

Imagine in your database you have Teams linked by ID to Players, which are linked by ID to Schools.

What if you want all teams with players that went to a school founded after 1950? Or if you wanted a team object with all members embedded? What if their school were also embedded to them?

mongo-join-query allows you to do exactly that. You can populate as many levels deep as you want.

Note: You need to be using Mongoose to specify your database schema.

Note: Requires Mongo >= v3.4.

mongoJoin(
    mongoose.models.Team,
    {
        find: { "members.studiedAt.yearFounded": { $gt: 1950 } },
        populate: ["members.studiedAt", "leader.studiedAt"],
        sort: { "members.age": 1 },
        skip: 10,
        limit: 1
    },
    (err, res) => (err ? console.log("Error:", err) : console.log("Success", res))
);

How does it work?

Behind the scenes the options object is transformed in different stages in an aggregation pipeline.

To see the entire aggregation pipeline being used add debug: true to the options object.

Limits and Contributing

You can populate an array field if it is a property of the main Model of the query. But you cannot populate an array field of linked models.

This is a shortcoming of the current implementation of the $group phase of the aggregation. If you would like to contribute with this project, this is the place to look at.

When contributing please make sure to include a failing test int he pull request.

Docs

The library exposes a single function which accepts three arguments:

mongoJoin(
    mongoose.models.Team, // The mongoose model on which to do the query
    options, // an options object
    callback // A callback
);

Options

// The options object accepts the follwing fields:
const options =
    {
        // A query where you can treat all populated paths as
        // embedded documents
        find: { "members.studiedAt.yearFounded": { $gt: 1950 } },
        // A list of strings defining all the paths you would like to populate.
        // In this case we are populating the `members` field in Team and
        // inside the members field we are populating `studiedAt`.
        //
        // If you want to populate multiple paths in subdocuments, just
        // list the entire paths. For example, imagine you want to populate
        // `members` and inside each member you want to populate both `studiedAt`
        // and `bestFriend`. You would use an array like this:
        //  ["members.studiedAt", "members.bestFriend"]
        populate: ["members.studiedAt", "leader.studiedAt"],
        // What you would normally pass to .sort()
        sort: { "members.age": 1 },
        // How many documents to skip
        skip: 10,
        // Maximum number of documents to be returned
        limit: 1,
        // If debug is true, it will print the aggregation pipeline used in the query.
        debug: false
    },

Callback

The callback takes two arguments:

  • error - An error object. If there is no error it will be null. If there is an error, it will looks like this:
    {   name: 'Invalid query',
        message: 'Invalid population path: Field nonExistent not found.',
        errors: []
    }
  • result - If there is an error, the result will be null. If there isn't it will look like this:
    {   name: 'Invalid query',
        message: 'Invalid population path: Field nonExistent not found.',
        errors: []
    }

Full Example

Here is an example:

const m = require("mongoose");
const mongoJoin = require("mongo-join-query");

const School = m.model(
    "School",
    m.Schema({
        name: String,
        yearFounded: Number
    })
);

const Player = m.model(
    "Player",
    m.Schema({
        name: String,
        age: Number,
        studiedAt: {
            type: m.Schema.Types.ObjectId,
            ref: "School"
        }
    })
);

const Team = m.model(
    "Team",
    m.Schema({
        name: String,
        leader: {
            type: m.Schema.Types.ObjectId,
            ref: "Player"
        },
        members: [
            {
                type: m.Schema.Types.ObjectId,
                ref: "Player"
            }
        ]
    })
);

m.connect("mongodb://localhost/test");
m.connection.once("open", () => {
    mongoJoin(
        m.models.Team,
        {
            find: { "members.studiedAt.yearFounded": { $gt: 1950 } },
            populate: ["members.studiedAt", "leader.studiedAt"],
            sort: { "members.age": 1 },
            skip: 10,
            limit: 1
        },
        callback
    );
});

function callback(error, res) {
    if (error) {
        console.log("An error occurred:", error);
        return;
    }

    console.log("Total of results found:", res.count);
    console.log("Values returned: ", JSON.stringify(res.results, null, 4));
    /*
    The result could look like this:

    Total of results found: 20
    Values returned:
        [
            {
                "_id": "5a304a75284c435f2d89d06a",
                "name": "team 3",
                "championships": 3,
                "leader": {
                    "_id": "5a304a75284c435f2d89d067",
                    "name": "Player 3",
                    "age": 27,
                    "studiedAt": {
                        "_id": "5a304a75284c435f2d89d064",
                        "name": "School 3",
                        "yearFounded": 1970,
                        "__v": 0
                    },
                    "__v": 0
                },
                "members": [
                    {
                        "_id": "5a304a75284c435f2d89d065",
                        "name": "Player 1",
                        "age": 25,
                        "studiedAt": {
                            "_id": "5a304a75284c435f2d89d062",
                            "name": "School 1",
                            "yearFounded": 1950,
                            "__v": 0
                        },
                        "__v": 0
                    },
                    {
                        "_id": "5a304a75284c435f2d89d066",
                        "name": "Player 2",
                        "age": 26,
                        "studiedAt": {
                            "_id": "5a304a75284c435f2d89d063",
                            "name": "School 2",
                            "yearFounded": 1960,
                            "__v": 0
                        },
                        "__v": 0
                    }
                ],
                "allMembers": [
                    "5a304a75284c435f2d89d065",
                    "5a304a75284c435f2d89d066",
                    "5a304a75284c435f2d89d067"
                ],
                "represents": "5a304a75284c435f2d89d064",
                "__v": 0,
                "_temp_leader0": {
                    "48772226526669904": "5a304a75284c435f2d89d067"
                },
                "_temp_studiedAt0": {
                    "16134390050729674": "5a304a75284c435f2d89d064"
                }
            }
        ]
     */
}