猫鼬中的自动增量ID

猫鼬中的自动增量ID

问题描述:

我如何在猫鼬中拥有自动递增的ID?我希望我的ID以1、2、3、4开头,而不是mongodb为您创建的怪异ID号吗?

How do I have autoincrement ids in mongoose? I want my ids to start like 1, 2, 3, 4, not the weird id numbers mongodb creates for you?

这是我的模式:

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-auto-increment: https://github.com/codetunnel/mongoose-auto-increment

Use mongoose-auto-increment: 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,只需添加该字段并在自动增量初始化中将其列出:

Or if you prefer to use an additional field instead of overriding _id, just add the field and list it in the auto-increment initialization:

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' });