当前位置 : 主页 > 网络编程 > JavaScript >

MongoDB 自增id

来源:互联网 收集:自由互联 发布时间:2021-06-28
Model.js const Mongoose = require('mongoose');const Schema = Mongoose.Schema;let counter = 1;let CountedId = {type: Number, default: () = counter++};const ModelSchema = new Schema({ id: CountedId, // ....});const Model = Mongoose.model('Mod
Model.js
const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;

let counter = 1;
let CountedId = {type: Number, default: () => counter++};

const ModelSchema = new Schema({
    id: CountedId,
    // ....
});

const Model = Mongoose.model('Model', ModelSchema);

module.exports = Model;

Model.find({ id: { $gt: 0 } }).sort({ id: -1 })
    .then(([first, ...others]) => {
        if (first)
            counter = first.id + 1;
    });
网友评论