Giter Site home page Giter Site logo

nodkz / mongoose-plugin-autoinc Goto Github PK

View Code? Open in Web Editor NEW
66.0 7.0 15.0 2.6 MB

Mongoose plugin that auto-increments any ID field on your schema every time a document is saved

JavaScript 98.87% Shell 1.13%
mongoose mongoose-plugin autoincrement

mongoose-plugin-autoinc's Introduction

mongoose-plugin-autoinc

codecov coverage Travis npm Commitizen friendly


This is a fork of mongoose-auto-increment which has not been maintained in a while. Also used fixes and changes from dashride fork. This fork addresses the following issues:

  • fix error 'required' is not valid for an index specification for Mongoose 4
  • does not require established connection for initialization (deprecate initialize() method)
  • include Flowtype and Typescript declarations
  • tested with Mongoose 5
  • setup automatic package publishing on PR merge with Travis CI and sematic-release

Getting Started

npm install mongoose-plugin-autoinc

Once you have the plugin installed it is very simple to use. Just pass autoIncrement to the plugin() function on your schema.

import mongoose from 'mongoose';
import { autoIncrement } from 'mongoose-plugin-autoinc';

const connection = mongoose.createConnection("mongodb://localhost/myDatabase");

const BookSchema = new mongoose.Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Author' },
  title: String,
  genre: String,
  publishDate: Date
});

BookSchema.plugin(autoIncrement, 'Book');
const Book = connection.model('Book', BookSchema);

That's it. Now you can create book entities at will and they will have an _id field added of type Number and will automatically increment with each new document. Even declaring references is easy, just remember to change the reference property's type to Number instead of ObjectId if the referenced model is also using the plugin.

const AuthorSchema = new mongoose.Schema({
  name: String
});

const BookSchema = new mongoose.Schema({
  author: { type: Number, ref: 'Author' },
  title: String,
  genre: String,
  publishDate: Date
});

BookSchema.plugin(autoIncrement, 'Book');
AuthorSchema.plugin(autoIncrement, 'Author');

Want a field other than _id?

BookSchema.plugin(autoIncrement, { model: 'Book', field: 'bookId' });

Want that field to start at a different number than zero or increment by more than one?

BookSchema.plugin(autoIncrement, {
  model: 'Book',
  field: 'bookId',
  startAt: 100,
  incrementBy: 100
});

Your first book document would have a bookId equal to 100. Your second book document would have a bookId equal to 200, and so on.

Want to know the next number coming up?

const Book = connection.model('Book', BookSchema);
Book.nextCount().then(count => {
  // count === 0 -> true
  const book = new Book();
  book.save(err1 => {
    // book._id === 0 -> true
    book.nextCount().then(count => {
      // count === 1 -> true
    });
  });
});

nextCount is both a static method on the model (Book.nextCount(...)) and an instance method on the document (book.nextCount(...)).

Want to reset counter back to the start value?

BookSchema.plugin(autoIncrement, {
  model: 'Book',
  field: 'bookId',
  startAt: 100
});

const Book = connection.model('Book', BookSchema),
book = new Book();

book.save(err => {
  // book._id === 100 -> true
  book.nextCount().then(count => {
    // count === 101 -> true
    book.resetCount().then(nextCount => {
      // nextCount === 100 -> true
    });
  });
});

mongoose-plugin-autoinc's People

Contributors

alexpchin avatar borodayev avatar forsakenharmony avatar lyskos97 avatar nodkz avatar sp3c1 avatar vittorio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongoose-plugin-autoinc's Issues

Potential enhancement

Create an option to make the field uneditable? At the moment, you'd have to write custom logic to prevent people from sending the incremented field along with a request?

CastError: Cast to string failed for value

out of nowhere started to give the following error.

I tried to find the error and arrived at yield IC.findOneAndUpdate({. that is receiving an object indoc.get(settings.groupingField)

mongoose: 5.11.4
nodejs: 12.20.0

CastError: Cast to string failed for value "{
  turma: [],
  status: true,
  infantil: false,
  deletar: false,
  tipo: 58862a828f3e2721f8d920ca
}" at path "groupingField" for model "IdentityCounter"
    at model.Query.exec (/var/www/api-nodejs/node_modules/mongoose/lib/query.js:4358:21)
    at /var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:17:8
    at Generator.next (<anonymous>)
    at step (/var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:177:191)
    at /var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:177:437
    at new Promise (<anonymous>)
    at /var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:177:99
    at createCounterIfNotExist (/var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:55:17)
    at /var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:64:15
    at Generator.next (<anonymous>)
    at step (/var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:177:191)
    at /var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:177:437
    at new Promise (<anonymous>)
    at /var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:177:99
    at preSave (/var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:125:18)
    at model.<anonymous> (/var/www/api-nodejs/node_modules/mongoose-plugin-autoinc/lib/index.js:313:7)
    at callMiddlewareFunction (/var/www/api-nodejs/node_modules/kareem/index.js:482:23)
    at next (/var/www/api-nodejs/node_modules/kareem/index.js:58:7)
    at Kareem.execPre (/var/www/api-nodejs/node_modules/kareem/index.js:86:8)
    at Kareem.wrap (/var/www/api-nodejs/node_modules/kareem/index.js:265:8)
    at model.$__validate (/var/www/api-nodejs/node_modules/kareem/index.js:375:11)
    at /var/www/api-nodejs/node_modules/mongoose/lib/document.js:2226:10 {
  messageFormat: undefined,

can anybody help me

Thanks.

Counter increments even if document validation fails

On trying to save a document that fails the Mongoose validation specified in the schema, the counter for the corresponding collection still gets incremented but the document does not get saved (as expected). This results in the auto incremented ids not being continuous.

Could we add a flag that checks if the validation fails for a document and not increment the counter in that case? I had a look at the pre hook on 'validate' and this could be a potential fix:

Replace:
if ((doc.isNew && !alreadyGetId) || settings.migrate) {

with:
if ((doc.isNew && !alreadyGetId && doc.validateSync === undefined) || settings.migrate) {

I'm not sure if this is the best way to achieve this, but this could be a start.

Since Updating to mongoose 5.0.2

Since updating, my test with async parallel:

it('should assign pids for parallel async parallel requests', done => {
    async.parallel(
      [
        function(cb) {
          User.create(
            {
              email: `testing+tenant${Math.floor(
                Math.random() * 1000000000000
              )}@pad.co.uk`,
              password: 'password',
              passwordConfirmation: 'password',
              firstName: 'Tenant',
              lastName: `Person ${Math.floor(Math.random() * 10000)}`,
              image: 'http://fillmurray.com/300/300',
              mobile: '+447441393986', // Alex hushed number
              role: 'tenant'
            },
            (err, docs) => {
              if (err) {
                throw cb(err);
              }
              cb(null, docs);
            }
          );
        },
        function(cb) {
          User.create(
            {
              email: `testing+tenant${Math.floor(
                Math.random() * 1000000000000
              )}@pad.co.uk`,
              password: 'password',
              passwordConfirmation: 'password',
              firstName: 'Tenant',
              lastName: `Person ${Math.floor(Math.random() * 10000)}`,
              image: 'http://fillmurray.com/300/300',
              mobile: '+447441393986', // Alex hushed number
              role: 'tenant'
            },
            (err, docs) => {
              if (err) {
                throw cb(err);
              }
              cb(null, docs);
            }
          );
        },
        function(cb) {
          User.create(
            {
              email: `testing+tenant${Math.floor(
                Math.random() * 1000000000000
              )}@pad.co.uk`,
              password: 'password',
              passwordConfirmation: 'password',
              firstName: 'Tenant',
              lastName: `Person ${Math.floor(Math.random() * 10000)}`,
              image: 'http://fillmurray.com/300/300',
              mobile: '+447441393986', // Alex hushed number
              role: 'tenant'
            },
            (err, docs) => {
              if (err) {
                throw cb(err);
              }
              cb(null, docs);
            }
          );
        }
      ],
      function(err, results) {
        if (err) {
          throw (err);
        }
        const pids1 = results.map(user => user.pid);
        const pids2 = [0, 1, 2];
        (JSON.stringify(pids1.sort()) === JSON.stringify(pids2.sort())).should
          .be.true;
        done();
      }
    );
  });

Throws an error:

Uncaught E11000 duplicate key error collection: pad-test.identitycounters index: field_1_groupingField_1_model_1 dup key: { : "pid", : "", : "User" }

@sp3c1 And I are looking into it at the moment... It looks like something to do with compound indexes? You said you tested with mongoose 5? However, the dependencies are not 5 - (I don't think). What version did you test with?

Any ideas?

schema.plugin() must be a function got object

I have a schema with

const mongoose = require('mongoose');
const autoIncrement = require('mongoose-plugin-autoinc');

// Initialize Auto Increment 
const connection = mongoose.createConnection("mongodb://localhost:27017/food");

const partnerSchema = new mongoose.Schema({
    partnerID: { type: Number, index: true, unique: true }
});

partnerSchema.plugin(autoIncrement, {
    model: 'Partner',
    field: 'partnerID',
    startAt: 100300,
    incrementBy: 3
});

When I run this I keep getting duplicate index error. Can you tell me where I am wrong ?

nextCount not work

I am using mongoose 5.0.6
below is my code:

var mongoose = require('mongoose')
  
mongoose.connect('mongodb://localhost/test')
var autoIncrement = require('mongoose-plugin-autoinc')
  
const MySchema = new mongoose.Schema({
  name: { type: String },
  fruitId: Number
})
    
MySchema.plugin(autoIncrement.plugin, {
  model: 'fruit',
  field: 'fruitId'
})

const MyModel = mongoose.model('Fruit', MySchema)
     
var a = new MyModel({
  name: 'stone',
})

a.save(function(err, model){
  if(err) console.log('Error:',err)
  else {
    console.log( 'nextCount', a.nextCount)
    a.nextCount(function(err, count){
      console.log('count:', count)
    })
  }
})

The count number never displayed. It seems nextCount don't accept a function as a argument.
console.log('nextCount', a.nextCount) shows below:
nextCount: function (groupingFieldValue) {
const doc = this;
const IC = getIC(doc.collection.conn);
return nextCount(IC, settings, groupingFieldValue);
}

Autoinc field within a group of documents

I found this plugin very useful for autoinc of the field within a whole collection. However, I'm curious about its application within some group of documents of a collection. Simple example - I have the following collection (just an example):

var Transaction = new Scheme({
  project_id: {type: Number},
  description: {type: String},
  transaction_entry_number: {type: Number}, // <<< to be autoinc given project_id
  ...
)}

Then I would like to insert three different documents - two docs for the project "1", and one - for the project "2".
What I want to see for project "1" having two entries with transaction_entry_number = 1 and transaction_entry_number = 2. And for project "2" - transaction_entry_number = 1.

So is there any way to do so with this plugin?

Thanks!

Auto Increment not stable, sometimes increment by 1 sometimes 2 or 3 even 4

I have use this package in my project to provide autoincrement by 1 every time a new records come in. But somehow I can see that the increment is not consistence like id 10 to id 13 to id 14 to id 17 etc etc. Wondering what is the problem here?

I am using version as below:
"mongoose-auto-increment": "^5.0.1",
"mongoose-plugin-autoinc": "^1.1.9",

And code to use this in model as below:
var mongoose = require('mongoose'),
mongoosePaginate = require('mongoose-paginate'),
Schema = mongoose.Schema;

var user = new Schema({ ...............long list of schema here.............. })

var mongoosePages = require('mongoose-pages');

var autoIncrement = require('mongoose-plugin-autoinc');

provider.plugin(autoIncrement.plugin, {model: 'user', field: 'unique_id', startAt: 1, incrementBy: 1});

Unable to install

npm i mongoose-plugin-autoinc results in:

npm WARN registry Unexpected warning for http://registry.npmjs.org/: Miscellaneous Warning EINTEGRIT
Y: sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q== i
ntegrity checksum failed when using sha512: wanted sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5p
OFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q== but got sha1-+PLIh60Qv2f2NPAFtph/7TF5qsg=. (2301 byte
s)
npm WARN registry Using stale package data from http://registry.npmjs.org/ due to a request error du
ring revalidation.
npm WARN gentlyRm not removing C:\Users\augdo\mongo-express-node-typescript\node_modules\.bin\karma.
cmd as it wasn't installed by C:\Users\augdo\mongo-express-node-typescript\node_modules\karma
npm WARN gentlyRm not removing C:\Users\augdo\mongo-express-node-typescript\node_modules\.bin\karma
as it wasn't installed by C:\Users\augdo\mongo-express-node-typescript\node_modules\karma
npm WARN @auth0/[email protected] requires a peer of @angular/common@>=4.3.0 but none is inst
alled. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/compiler@^2.3.1 || >=4.0.0-beta <6.0.0 but none
 is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@^2.3.1 || >=4.0.0-beta <6.0.0 but none is
installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/platform-browser-dynamic@^2.3.1 || >=4.0.0-beta
 <6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/platform-browser@^2.3.1 || >=4.0.0-beta <6.0.0
but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/common@^2.3.1 || >=4.0.0-beta <6.0.0 but none i
s installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of joi@* but none is installed. You must install p
eer dependencies yourself.
npm WARN [email protected] requires a peer of karma@* but none is installed. You must install peer
 dependencies yourself.
npm WARN [email protected] requires a peer of karma@>=0.9 but none is installed. You
 must install peer dependencies yourself.
npm WARN [email protected] requires a peer of mongoose@^4.1.12 but none is installed. Yo
u must install peer dependencies yourself.
npm WARN [email protected] requires a peer of request@^2.34 but none is installed. You must inst
all peer dependencies yourself.
npm WARN [email protected] requires a peer of mongoose@>=4.0.0 || >=5.0.0 but none is in
stalled. You must install peer dependencies yourself.

npm ERR! Cannot read property '0' of undefined

Am I the only one, here?

Fix babel-runtime

Hi, mongoose-plugin-autoinc works great on create. However, when I try to update using findOneAndUpdate from mongoose, it creates another entry in the database, with incremented _id. But what I want is just update the existing entry without incrementing the _id field; it should increment only on document.create.
How can I achieve this?

By the way, I had to install babel-runtime because mongoose-plugin-autoinc didn't do it automatically.

How to implement autoinc in existing project?

Hi,
I'm using autoinc in a new project and so far, it's working very well. Now, I'd like to use autoinc in an existing project of mine; could you tell me how to apply autoinc to already existing entries in my database?

Thanks.

Is it possible to NOT have this plugin run when doing a model.validate()?

Is it possible to NOT have this plugin run when doing a model.validate(), and only make it run on a save method? I'm using the model to carry out primary validation of an object before carrying out separate rules based validation. If both validation steps pass, then I save the entry into the DB. In this setup, the autoinc entries in the DB count up in 2's rather tha 1's.

startAt Not working

Thank you for rescuing this package from the dead guys.

This was an issue with the previous package as well, but the startAt function doesn't work. I've also just tried saving a schema twice... and both don't increment at all. So it could be an issue stemming deeper than just startAt

Increment sub document field

Hi all,
i want to use auto increment for my subdocument array structure in mongoose.

const schema=new Schema({
	sectoreName: String,
	members:[{
		_id: false,
		m_id:Number
	}]	
})

I want to set autoincrement to members.m_id .
How to do it ???
Please help for this

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.