【问题标题】:How to implement auto increment for mongodb in strapi?如何在strapi中实现mongodb的自动增量?
【发布时间】:2019-11-05 17:36:58
【问题描述】:

我尝试将这些猫鼬插件mongoose-auto-incrementmongoose-sequence 添加到config/functions/mongoose.js 中的strapi.. 正在创建计数器集合.. 但是序列计数没有更新.. 有没有办法获得这些插件工作还是有办法自己实现它?

// 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 });
};

【问题讨论】:

    标签: javascript mongodb mongoose strapi


    【解决方案1】:

    在类似的情况下,我使用一个新的 Schema 作为 Id 的计数器来解决它。

    这是计数器架构 (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();
    }
    

    Movie Schema 将是 (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;
    });
    

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      我的解决方法是使用单一类型作为计数器。

      每次我需要使用和递增计数器时,我都会获取计数器单一类型并使用内置的 createOrUpdate 服务来获取数字。

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

      我知道单一类型不适用于此,但它有效且易于处理。

      希望能帮助别人

      【讨论】:

        猜你喜欢
        • 2012-09-08
        • 1970-01-01
        • 2017-12-31
        • 1970-01-01
        • 1970-01-01
        • 2015-12-31
        • 2021-06-20
        • 2021-05-09
        • 1970-01-01
        相关资源
        最近更新 更多