“Incremento automático de mangusto” Respostas de código

ID do esquema de incremento automático

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 mangusto

// 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

Crie um incremento automático 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

Respostas semelhantes a “Incremento automático de mangusto”

Perguntas semelhantes a “Incremento automático de mangusto”

Mais respostas relacionadas para “Incremento automático de mangusto” em JavaScript

Procure respostas de código populares por idioma

Procurar outros idiomas de código