我尝试将这些猫鼬插件mongoose-auto-increment
和mongoose-sequence
添加到config/functions/mongoose.js
中的bandi中。创建了计数器集合。但是序列计数没有得到更新。使这些插件正常工作的方法还是自己实现的方法?
// 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 });
};
答案 0 :(得分:0)
在类似的情况下,我使用新的架构作为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();
}
电影模式为(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;
});
希望有帮助!
答案 1 :(得分:0)
我的解决方法是使用单一类型作为计数器。
每次我需要使用和递增计数器时,我都会得到计数器单一类型,并使用内置的 createOrUpdate 服务来获取数字。
const counters = await strapi.services.counters.find();
const updatedCounter = await strapi.services.counters.createOrUpdate({
ainumber : counters.ainumber + 1,
});
我知道单一类型不适用于此,但它有效且易于处理。
希望对某人有帮助