📜  自动递增模式猫鼬 id - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:01:25.258000             🧑  作者: Mango

代码示例1
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);