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

egg-mongodb

v1.1.1

Published

A mongodb adapter for egg.js

Downloads

32

Readme

egg-mongodb

A mongodb adapter for egg.js

Install

npm i egg-mongodb --save

Config

add configure in your config.default.js or other environment.

   module.exports = appInfo => {
        const config = {};

        // add your config here
        config.mongodb = {
            app: true,
            agent: false,
            username: '',
            password: '',
            hosts: '127.0.0.1:27017',
            db: 'test',
            query: '',
            // defalut: {
            //     username: '',
            //     password: '',
            //     hosts: '127.0.0.1:27017',
            //     db: 'test',
            //     query: ''
            // },
            // client: {
            //     username: '',
            //     password: '',
            //     hosts: '127.0.0.1:27017',
            //     db: 'test',
            //     query: ''
            // }
        };

        return config;
   }

open this plugin in your plugin.js like this.

    exports.mongodb = {
        enable: true,
        // feel free to make some local change, and require it like this.
        // path: your_local_folder_path
        package: 'egg-mongodb'
    };

The mongodb connect string parse logic is like this.

    let url = 'mongodb://';

    if (config.username) {
        if (config.password) {
            url += `${config.username}:${config.password}@`;
        } else {
            url += `${config.username}@`;
        }
    }

    url += `${config.hosts}/${config.db}`;

    if (config.query) {
        url += `?${config.query}`;
    }

Since the mongodb connection string is parsed in offical driver, it's no need to define multi clients in egg.js config.

Usage

After add this plugin in your application, an Object named mongodb will be added to the app instance. You can access it like this.

In your controller file:

    'use strict';

    module.exports = app => {
        class UserController extends app.Controller {
            async search() {
                let db = this.app.mongodb;

                let result = await db.collection('user').findOne({
                    // some query here
                    name: 'xxmy'
                }, {
                    name: 1,
                    phone: 1
                });

                this.ctx.body = result;
            }
        }
    }

Or in your service file:

    'use strict';

    module.exports = app => {
        class UserService extends app.Service {
            async register() {
                let db = this.app.mongodb;

                let User = db.collection('user');

                let rs;
                try {
                    let info = await User.insertOne({
                        name: 'zhang san',
                        phone: '177xxxxxxxx'
                    });

                    this.app.logger.log(info);

                    rs = {
                        code: '0',
                        content: 'user register ok'
                    }
                } catch (e) {
                    this.app.logger.error(e && e.stack);

                    rs = {
                        code: '-1',
                        content: e.message || 'unknown error'
                    }
                }

                return rs;
            }
        }

        return UserService;
    };

A mongodb Object is a fully proxy of original mongodb connection object proxy and contains some suger, constructor like this.

    mongodb = {
        ObjectId: 'a copy of mongodb\'s ObjectId function, you can access & make unique id easily',
        ObjectID: 'alias for ObjectId',
        url: 'mongodb connect string parsed from eggjs config',
        destroy: 'flag to mark whether the connection is keep alive',
        connect: 'packaging the MongoClient connect function, SHALL NOT call it manually.',
        '[Symbol]linkDB': 'original db connection Object link, and should be unchangable.',
        collection: 'proxy of original db.collection function'
    }

Notice: connect function will be called at start of the app, there is no need to call it manually.

See more detail of constructor here;

Todo & Warn

The url, destroy' and connectattribute inmongodb` instance is useless and may cause some security issues.

AND DO NOT TRY TO EDIT THESE ATTRS MANUALLY.

These problems should be fixed after.

Thanks To

This package is almost a fully copy from brickyang 's egg-mongo. Just removing some unnecessary functions and make it more easy to use.