首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在strapi中实现mongodb的自动增量?

如何在strapi中实现mongodb的自动增量?
EN

Stack Overflow用户
提问于 2019-06-24 04:52:12
回答 2查看 1.4K关注 0票数 3

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

代码语言:javascript
复制
// 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 });
};
EN

回答 2

Stack Overflow用户

发布于 2019-06-24 05:20:19

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

下面是计数器模式(model/coun.js):

代码语言:javascript
复制
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是(Movie Schema/Movie.js):

代码语言:javascript
复制
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;
});

希望它能帮上忙!

票数 0
EN

Stack Overflow用户

发布于 2021-01-29 18:51:08

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

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

代码语言:javascript
复制
const counters = await strapi.services.counters.find();

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

我知道单类型不适用于此,但它可以工作并且易于处理。

希望能帮助别人

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56727649

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档