Code Monkey home page Code Monkey logo

mongoose-idexists's Introduction

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

mongoose-idexists's People

Contributors

h4t0n avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

mongoose-idexists's Issues

Validation of Array with duplication is wrong

lets assume we have mode:

const Test = new Schema({
name: { type: String, required: true, unique: true },
scenarios: [{
type: Schema.Types.ObjectId,
ref: 'Scenario'
}]
})

and to create this entity we create from Mode:
test= {
name: "MosheReubinoff",
scenarios:[
"some_hash_type_A",
"some_hash_type_A"
]}

this will failed in validation because you check the count of scenarios which return 1 although we actually have 2.

in my opinion we need first to remove duplications from original array and to check the count against this list.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.