“incremento automático de mangosta” Código de respuesta

esquema de incremento automático identificación de mangosta

You can use this plugin: https://www.npmjs.com/package/mongoose-auto-increment

First you need to initialize it after creating Mongoose connection:

const connection = mongoose.createConnection("mongodb://localhost/myDatabase");
 
autoIncrement.initialize(connection);
Than in your subs.model.js file:

const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');

var subscriberSchema = new mongoose.Schema({
    _id: {type: String, required: true},
    email: {
        type: String
    }
}, {
    versionKey: false,
    collection: 'subscribers'
});

subscriberSchema.plugin(autoIncrement.plugin, {
    model: 'Subscribers',
    field: '_id'
});

module.exports = mongoose.model('Subscribers', subscriberSchema);
Zarden

incremento automático de mangosta

// schema creation...

let modal;
SchemaVariable.pre('save', function(next) {
  if (this.isNew) {
    if (!modal) {
      modal = mongoose.model('collectionname');
    }
    modal.find({})
      .then((entries) => {
        this._id = entries.length + 1;
        next();
      })
  }
});
Stupid Someone

Crea Auto Incremento MongoDB Mongoose

// using pre('save' on your mongoose schema

// creating the counter collection/model to save the number of documents:
const counterCollection = mongoose.model('counter',
	new mongoose.Schema({number: Number}), 'counter')

// updating the counter and the pre-saved document that need the index/number
documentSchema.pre('save', async function() {
  if(this.number) {
    let counterDoc = await counterCollection.findOne()
    if(!counterDoc) {
      counterDoc = new counterCollection({number: 1})
    } else {
      counterDoc.number++
    }
    this.number = counterDoc.number
    const response = await counterDoc.save()
  }
})
// don't forget to update the schema with the number key-value pair to
// store the number, so mongoose does not throw error
Graceful Grivet

Respuestas similares a “incremento automático de mangosta”

Preguntas similares a “incremento automático de mangosta”

Más respuestas relacionadas con “incremento automático de mangosta” en JavaScript

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código