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

v1.0.5

Published

Mongoose Validator to checks if the ref Object ID exists

Downloads

11

Readme

mongoose-idexists

NPM Version Travis Build

Mongoose plugin that checks if referenced documents actually exist.

This plugin can be used to validate Mongoose Schema paths that are referencing other documents (usually by mongoose ObjectId of the _id field). It can be used as a full plugin that recursively add a validator to each ref path, or it can also be used to protect single schema paths.

Usage

Install

Simply run:

$ npm install mongoose-idexists --save

Then require it in your project

var idexists = require('mongoose-idexists');

Basic Usage (default mongoose connection)

If you use idexists without any further configuration, it uses the default mongoose connection.

You can add an idexists validator for each Schema paths you want by using idexists.forPath(_the_mongose_path_object)

// require the idexists plugin
var idexists = require('mongoose-idexists');

// Let's define some schemas with ref fields
var personSchema = new Schema({
    name: String,
});

var storySchema = new Schema({
    _creator: {
        type: Schema.Types.ObjectId,
        ref: 'Person'
    },
    fans: [{
        type: Schema.Types.ObjectId,
        ref: 'Person'
    }]
});

// Let's add the validator only to the _creator path
idexists.forPath(storySchema.path("_creator"));

Array of references are supported. So you can use.

// Add the validator also to fans array
idexists.forPath(storySchema.path("fans"));

You can also recursively add a validator to all the Schema paths (that have references to other documents).

// Let's add the validator to _creator and fans at the same time
idexists.forSchema(storySchema);

// As an alternative you can also use the mongoose plugin notation
storySchema.plugin(idexists.forSchema)

// both previous notation produce the same effects of
idexists.forPath(storySchema.path("_creator"));
idexists.forPath(storySchema.path("fans"));

After the Schema definition as usual you can create the mongoose model. The previous code works for default mongoose connection, so somewhere after configuration you have to use

Story = mongoose.model('Story', storySchema);
Person = mongoose.model('Person', personSchema);

Custom Connection

If you want to use a mongoose custom connection, you have to configure idexists options.

The easies and comfortable way is to setup the connection as a global ìdexists option, so it is used each time you use forSchema or forPath methods.

// Let's configure ìdexists in order to use a custom configuration
// require the idexists plugin
var idexists = require('mongoose-idexists');

// during init phase
var connection = mongoose.createConnection(_url_);
idexists.setOptions({
    connection: connection
});

// after initialization you can use forPath and forSchema, that now use the custom connection
idexists.forPath(storySchema.path("_creator"));

You can also specify a custom connection exclusively for some paths or schemas:

// during init phase
var connection = mongoose.createConnection(_url_);

// validator for _creator path uses the custom connection
idexists.forPath(storySchema.path("_creator",{
  connection: connection
});

// validator for fans path uses the default mongoose connection
// (or the one specified by init setOptions configuration)
idexists.forPath(storySchema.path("fans"));

// validator for anotherSchema paths uses the custom connection
idexists.forSchema(anotherSchema,{
  connection: connection
});

Validation Messages

Default validation error messages use the following pattern:

{PATH} document not found in {MODEL} collection

where PATH is substituted with the schema path that causes the validation error, while MODEL is the referencing model, for example for the code seen before we have this validation error for PATH _creator:

_creator document not found in Person collection

Custom Messages

To add a custom Message you can configure idexists options globally:

idexists.setOptions({
    message: "custom Message {MODEL}"
});

Note that you can use the {MODEL} keyword in your string to indicate the referencing model (in addition to default keywords).

You can also specify a custom message exclusively for some paths or schemas:

idexists.forPath(storySchema.path("fans"), {
    message: "another custom Message {MODEL}"
});

idexists.forSchema(storySchema, {
    message: "another custom Message {MODEL}"
});

You can combine configuration for custom messages and connection both for global options and single path or schema options:

idexists.setOptions({
    connection: connection
    message: "custom Message {MODEL}"
});

idexists.forPath(storySchema.path("fans"), {
    message: "another custom Message {MODEL}",
    connection: connection
});

idexists.forSchema(storySchema, {
    message: "another custom Message {MODEL}",
    connection: connection
});

storySchema.plugin(idexists.forSchema, {
    message: "another custom Message {MODEL}",
    connection: connection
});

How it works

The plugin is very simple, it perform a simple count query (by using TargetModel.count) filtered by the referencing id. The count returning value is checked accordingly to the referencing field type (single object or array).

NB the filter query uses the _id field (it works as population).

Test

Tests require a local mongodb database running with default configuration.

$ npm test

License

MIT © Andrea Tarquini