gpt4 book ai didi

mongodb - Mongoose 中的自动递增ID

转载 作者:可可西里 更新时间:2023-11-01 09:59:00 25 4
gpt4 key购买 nike

如何在 mongoose 中使用自动增量 ID?我希望我的 ID 以 1、2、3、4 开头,而不是 mongodb 为您创建的奇怪 ID 数字?

这是我的架构:

var PortfolioSchema = mongoose.Schema({
url: String,
createTime: { type: Date, default: Date.now },
updateTime: { type: Date, default: Date.now },
user: {type: Schema.Types.ObjectId, ref: 'User'}
});

最佳答案

使用 mongoose 自动增量: https://github.com/codetunnel/mongoose-auto-increment

var mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
var connection = ....;
autoIncrement.initialize(connection);

var PortfolioSchema = new mongoose.Schema({
url: String,
createTime: { type: Date, default: Date.now },
updateTime: { type: Date, default: Date.now },
user: {type: Schema.Types.ObjectId, ref: 'User'}
});

//Auto-increment
PortfolioSchema.plugin(autoIncrement.plugin, { model: 'Portfolio' });

module.exports = mongoose.model('Portfolio', PortfolioSchema);

或者,如果您更喜欢使用附加字段而不是覆盖 _id,只需添加该字段并将其列在自动增量初始化中:

var PortfolioSchema = new mongoose.Schema({
portfolioId: {type: Number, required: true},
url: String,
createTime: { type: Date, default: Date.now },
updateTime: { type: Date, default: Date.now },
user: {type: Schema.Types.ObjectId, ref: 'User'}
});

//Auto-increment
PortfolioSchema.plugin(autoIncrement.plugin, { model: 'Portfolio', field: 'portfolioId' });

关于mongodb - Mongoose 中的自动递增ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685250/

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