MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

IDs de incremento automático no mangusto


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

Ou se preferir usar um campo adicional em vez de substituir _id , basta adicionar o campo e listá-lo na inicialização do incremento automático:
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' });