How to insert auto increment number in mongoose

好久不见. 提交于 2020-07-26 19:25:08

问题


Tried to insert auto increment number for serial number in mongodb using mongoose and nodejs but not working.Where i want to update my code to find solution.If anyone knows please help to find solution.

subs.model.js:

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

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

data.controller.js:

module.exports.subscribeMail = (req, res, next) => { 
    var subscribeModel = mongoose.model("Subscribers");
    var subscribemailid = req.query.email;
    var subscribe = new subscribeModel({
        email: subscribemailid
    });

    var entitySchema = mongoose.Schema({
        testvalue: { type: String }
    });
 
    subscribe.save(function(error, docs) {
        if (error) { console.log(error); } else {
            console.log("subscribe mail id inserted");
            console.log(docs)
            res.json({ data: docs, success: true });
        }
    });

    entitySchema.pre('save', function(next) {
        var doc = this;
        subscribe.findByIdAndUpdate({ _id: 'entityId' }, { $inc: { seq: 1 } }, function(error, counter) {
            if (error)
                return next(error);
            doc.testvalue = counter.seq;
            next();
        });
    });
};

If i use above code inserting data into mongodb like below:

_id:5f148f9264c33e389827e1fc
email:"test@gmail.com"

_id:6f148f9264c33e389827e1kc
email:"admin@gmail.com"

But i want to insert like this

_id:5f148f9264c33e389827e1fc
serialnumber:1
email:"test@gmail.com"

_id:6f148f9264c33e389827e1kc
serialnumber:2
email:"admin@gmail.com"

回答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: 'serialnumber'
});

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


来源:https://stackoverflow.com/questions/62998085/how-to-insert-auto-increment-number-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!