How to implement auto increment for mongodb in strapi?

Viewed 1674

i tried adding these mongoose plugins mongoose-auto-increment and mongoose-sequence to strapi in config/functions/mongoose.js.. the counter collections are getting created.. but the sequence counts are not getting updated.. Is there a way to get these plugins working or is there a way to implement it myself?

// config/functions/mongoose.js
var autoIncrement = require('mongoose-auto-increment');

module.exports = (mongoose, connection) => {
  autoIncrement.initialize(mongoose.connection);

  var movieSchema = mongoose.Schema({
    title: String
  }, { collection : 'Tests' });

  movieSchema.plugin(autoIncrement.plugin, { model: 'Test', field: 'movieId', startAt: 1 });
};
2 Answers

In a similar situation I solved it using a new Schema as a Counter for the Ids.

Here is the Counter Schema (models/counter.js):

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CounterSchema = Schema({
    _id: {
        type: String,
        required: true
    },
    sequence: {
        type: Number,
        default: 0
    }
}, {
    collection: 'counters'
});

// export the counter model below and call this method to create the first entry in the counter's table
CounterSchema.statics.createFirstIdForMovie = async () => {        
  const newCounter = new counter({
      _id: "movieid",
      sequence: 0
  });
   newCounter.save();
}

And the Movie Schema would be (models/movie.js):

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const MovieSchema = new Schema({
    ...,
    identifier: {
        type: Number,
        required: false,
        unique: true
    },
    ...
});

MovieSchema.pre('save', async function (next) {
    // get the next value for the identifier of 'movieid'
    if (this.identifier) {
        // just editing, don't need to increment or set a new identifier
        return;
    }
    let c = await counter.findById('movieid');
    if (!c) {
        c = await counter.createFirstIdForMovie();
    }
    c.sequence += 1;
    await c.save();
    this.identifier = c.sequence;
});

Hope it helps!

My workaround was to use a single-type as counter.

Each time I need to use and increment the counter I get the counter single-type and use the built-in createOrUpdate service to get the number.

const counters = await strapi.services.counters.find();

const updatedCounter = await strapi.services.counters.createOrUpdate({
  ainumber : counters.ainumber + 1,
});

I know single-types are not ment for this, but it works and is easy to handle.

Hope helps someone

Related