MongoDB
 sql >> Baza danych >  >> NoSQL >> MongoDB

Utwórz unikalne pole autoinkrementacji z mangustą

const ModelIncrementSchema = new Schema({
    model: { type: String, required: true, index: { unique: true } },
    idx: { type: Number, default: 0 }
});

ModelIncrementSchema.statics.getNextId = async function(modelName, callback) {
    let incr = await this.findOne({ model: modelName });

    if (!incr) incr = await new this({ model: modelName }).save();
    incr.idx++;
    incr.save();
    return incr.idx;
};


const PageSchema = new Schema({
    id: { type: Number ,  default: 0},
    title: { type: String },
    description: { type: String }
});


PageSchema.pre('save', async function(next) {
    if (this.isNew) {
        const id = await ModelIncrement.getNextId('Page');
        this.id = id; // Incremented
        next();
    } else {
        next();
    }
});


  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Wykonywanie zapytań regex za pomocą PyMongo

  2. Obraz zwrócony z REST API zawsze wyświetla uszkodzony

  3. Importuj dane CSV jako tablicę w MongoDB za pomocą mongoimport

  4. Planowanie i zarządzanie schematami w MongoDB (nawet jeśli nie jest to schemat)

  5. 3 proste kroki, aby poprawić bezpieczeństwo instalacji MongoDB