Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@kolinalabs/mongoose-consistent

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@kolinalabs/mongoose-consistent

Foreign reference check across collections with mongoose

  • 0.3.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

mongoose-consistent

Foreign reference check across collections with mongoose.

travis npm downloads

Mongoose allows models from different collections to be related by some type of reference (ref, refPath, array of ObjectIds). However, document deletion operations associated with documents from another collection, end up affecting the consistency of these relationships.

This library aims to provide mechanisms in an attempt to maintain the relational integrity between documents of different models, using their reference identifiers (_id), as well as types of action (restrict, set_null or cascade), in order to apply constraints similar to those of relational databases, however application level.


>> CHECK THE SAMPLE PROJECT <<



// The parent schema
const CategorySchema = new mongoose.Schema({
  name: String,
  description: String,
  position: Number,
})

// The child schema
const ProductSchema = new mongoose.Schema({
  name: String,
  price: Number,
  category: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Category',
    /**
    * set_null: Field is set to null
    * no_action: Ignores reference check
    * cascade: This document is removed
    * restrict: DeleteConstraintError is dispatched
    * {Function}: Executes a callback function
    */
    onDelete: 'restrict',
    /**
    * true: Handle reference check (enabled)
    * false: Ignores reference check (disabled)
    * {Function}: Executes a callback function
    */
    saveCheck(context) {
      // Do whatever you want
      // console.log(context)
    }
  }
}

Supported API methods

SaveDelete
Document.saveDocument.delete
Document.updateModel.deleteOne
Document.updateOne
Model.findByIdAndUpdateModel.findByIdAndDelete
Model.findOneAndReplaceModel.findByIdAndRemove
Model.findOneAndUpdateModel.findOneAndDelete
Model.insertManyModel.findOneAndRemove
Model.replaceOneModel.delete
Model.updateModel.remove
Model.updateOneModel.deleteOne
Model.updateManyModel.deleteMany
Query.findOneAndReplaceQuery.deleteOne
Query.findOneAndUpdateQuery.deleteMany
Query.replaceOneQuery.findOneAndDelete
Query.updateQuery.findOneAndRemove
Query.updateOneQuery.remove
Query.updateMany

Usage

Recommended global installation only.

Note: Configure this plugin before loading models.

    const mongoose = require('mongoose')

    mongoose.plugin(require('@kolinalabs/mongoose-consistent'), {
        eventKey: 'on_delete',      // onDelete (default)
        actionDefault: 'set_null',  // restrict (default)
        saveCheckDefault: false     // true (default)
    })

Options

Optiondefaultdescription
eventKeyonDeleteChange the configuration property on the schema
actionDefaultrestrictchange the default action applied when a referral is found
saveCheckDefaulttrueenable (true), disable (false) or custom (callback) saveCheck

Actions for delete constraint

restrict:

An error is thrown when attempting to delete a parent record.

Dispatches DeleteConstraintError instance with a similar error message:

Cannot delete a parent doc: ref constraint fails (ChildModel.parent_field)
{
  onDelete: 'restrict'
}

cascade:

All child records are removed.

{
  onDelete: 'cascade'
}

set_null:

Sets the referenced property in the children to null.

{
  onDelete: 'set_null'
}

no_action:

Ignore reference check.

{
  onDelete: 'no_action'
}

callback:

Use a function to control the behavior of the operation.

{
  onDelete(context) {
      // console.log(context)
  }
}
// The 'context' object passed to the callback
{
  config: {
    modelName: 'ItemB',
    pathName: 'refArrayOfObjectRelated.$.itemA',
    modelRefs: ['ItemA'],
    action: 'cascade'
  },
  conditions: {
    'refArrayOfObjectRelated.itemA': {
      '$in': ['60c8e0c2cc629121ac49db5b']
    }
  },
  identifiers: ['60c8e0c2cc629121ac49db5b'],
  targetPath: 'refArrayOfObjectRelated.itemA',
  countRef: 5
}

saveCheck for save constraint

true:

Active check during document saving.

Dispatches SaveConstraintError instance with a similar error message:

Cannot add or update a child doc: a foreign key constraint fails ('dbname'.'child_collection', CONSTRAINT 'ParentModel._id#ChildModel.parent_field' FOREIGN KEY ('parent_field') REFERENCES 'parent_collection' ('_id'))
{
  saveCheck: true
}

false:

Inactive check during document saving.

{
  saveCheck: false
}

callback:

Use a function to control the behavior of the operation.

{
  saveCheck(context) {
      // console.log(context)
  }
}
// The 'context' object passed to the callback

{
    config: {
        modelName: 'ChildModel',
        pathName: 'parent',
        modelRefs: ['ParentModel'],
        action: 'restrict',
        saveCheck: true,
    },
    dbName: 'yourdbname',
    childModel: 'ChildModel',
    parentModel: 'ParentModel',
    childKey: 'parent',
    parentKey: '_id',
    childCollection: 'child_collection_name',
    parentCollection: 'parent_collection_name',
    identifier: '60e630a00f29040340f556b7',
}

Note

Similar to what happens in relational databases, this configuration must occur in the child schema, corresponding to the weak side of the relationship (ex: 1:N [this side])

Configuration behavior for delete actions

Associationrestrictcascadeset_null
ref (ObjectId)Errordocument is removedfield is null
refPathErrordocument is removedfield is null
array of ObjectIdErrordocument is removedarray item is removed
array of SubdocumentsErrorsubdocument is removedproperty of subdocument is null

Keywords

FAQs

Package last updated on 08 Jul 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc