gpt4 book ai didi

javascript - 如何在strapi中为mongodb实现自增?

转载 作者:可可西里 更新时间:2023-11-01 10:45:04 24 4
gpt4 key购买 nike

我尝试将这些 Mongoose 插件 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 });
};

最佳答案

在类似的情况下,我使用新架构作为 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;
});

希望对您有所帮助!

关于javascript - 如何在strapi中为mongodb实现自增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56727649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com