我尝试将这些mongoose插件mongoose-auto-increment和mongoose-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 });
};发布于 2019-06-24 05:20:19
在类似的情况下,我使用一个新的Schema作为Ids的计数器来解决它。
下面是计数器模式(model/coun.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是(Movie Schema/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;
});希望它能帮上忙!
发布于 2021-01-29 18:51:08
我的变通方法是使用单一类型作为计数器。
每次我需要使用和递增计数器时,我都会获得单一类型的计数器,并使用内置的createOrUpdate服务来获取数字。
const counters = await strapi.services.counters.find();
const updatedCounter = await strapi.services.counters.createOrUpdate({
ainumber : counters.ainumber + 1,
});我知道单类型不适用于此,但它可以工作并且易于处理。
希望能帮助别人
https://stackoverflow.com/questions/56727649
复制相似问题