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

mongodb-n

v1.2.6

Published

The main reason I created this module is to retrieve normalized data from MongoDB and still keep the native awesome API provided by `mongodb` module. If you're looking for something fancier you should try Mongoose.

Downloads

6

Readme

The main reason I created this module is to retrieve normalized data from MongoDB and still keep the native awesome API provided by mongodb module. If you're looking for something fancier you should try Mongoose.

import { FieldTypes, Schema, createModels } from 'mongodb-n';

// user.js
const User = new Schema({
  collection: 'users',
  fields: {
    name: FieldTypes.String
  }
});

// comment.js
const Comment = new Schema({
  collection: 'comments',
  fields: {
    body: FieldTypes.String,
    postId: FieldTypes.ObjectId
  }
});

// post.js
const Post = new Schema({
  collection: 'posts',
  fields: {
    title: FieldTypes.String,
    authorId: {
      type: FieldTypes.ObjectId | FieldTypes.SchemaReference,
      reference: User
    },
    comments: {
      type: FieldTypes.ArrayOf | FieldTypes.ForeignerReference | FieldTypes.ObjectId,
      property: 'postId',
      reference: Comment
    }
  }
});

// models/index.js
module.exports = async function createModels() {
  createModels(await MongoClient.connect('mongodb://localhost/well_designed_db', {
    promiseLibrary: require('bluebird')
  }), {
    User,
    Post,
    Comment
  });
};

Usage

const [user] = await models.User.insertOne({
  name: 'John Wick'
});
const [post] = await models.Post.insertOne({
  title: 'First post',
  authorId: user._id
});
const [comment] = await models.Comment.insertOne({
  body: 'this is my first comment',
  postId: post._id
});

assert.deepEqual(await models.Post.find().toArray(), {
  users: [{
    _id: user._id,
    name: 'John Wick'
  }],
  comments: [{
    _id: comment._id,
    body: 'this is my first comment',
    postId: post._id
  }],
  posts: [{
    _id: post._id,
    title: 'First post',
    authorId: user._id
  }]
});

Conditional schemas

We can use this feature for when a content of a specific field depend specifically on the raw MongoDB document content. For example, if we have a timeline in which the contents attribute depends specifically in what is present on type attribute, we should have a schema like this:

const Timeline = new Schema({
  collection: 'timeline',
  fields: {
    type: {
      type: FieldTypes.String,
      validation: [Validators.required]
    },
    contents: {
      type: FieldTypes.ConditionalSchema,
      getSchema: function({ type }){
        switch(type){
          case Timeline.Types.UserFavoriteProduct:
            return new Schema({
              userId: {
                type: FieldTypes.ObjectId | FieldTypes.SchemaReference,
                reference: User
              },
              productId: {
                type: FieldTypes.ObjectId | FieldTypes.SchemaReference,
                reference: Product
              },
              date: FieldTypes.Number
            });
        }
      }
    }
  }
});

Timeline.Types = {
  UserFavoriteProduct: 'Timeline/UserFavoriteProduct'
};

Validation

Generally validators will be used during insertOne, insertMany, updateOne and updateMany operations.

import { Validators, FieldTypes, Schema } from 'mongodb-n';

const customTitleValidator = Validators.createValidator('customTitleValidator', function(field, value) {
  return /^[A-z0-9]+$/.test(value);
});

new Schema({
  title: {
    type: FieldTypes.String,
    validation: [Validators.required, Validators.max(255), customTitleValidator]
  },
  emailAddress: {
    type: FieldTypes.String,
    validation: [
      Validators.required,
      Validators.unique(
        'users' /* collection */,
        'email' /* collection document property */
      )
    ]
  }
});

If an invalid field is found, a proper error will be throwed in the promise. And it could be handled like:

UserController.prototype.createUser = async function createUser() {
  try {
    return await models.User.insertOne({
      title: '****'
    });
  } catch(reason) {
    if(reason.message === 'ER_MONGODB_VALIDATION') {
      // Handle it through `reason.errors` expression
    } else {
      // Do something else
    }
  }
};