【问题标题】:how can I create a auto-increment field in mongoose如何在猫鼬中创建自动增量字段
【发布时间】:2017-06-01 03:04:49
【问题描述】:

谁能告诉我如何在不使用任何库或插件的情况下在 mongoose 中创建一个自动增量字段。任何简单易行的方法..

【问题讨论】:

标签: node.js mongoose mongoose-schema mongoose-auto-increment


【解决方案1】:

使用 mongoose pre save 功能可以在 mongoose 中实现自动增量,这是一种非常简单易行的方法。这是我的用户收集代码,在您的 mongoose 模型(模式) 中尝试相同的技巧来实现自动增量。将此代码粘贴到您的集合架构文件中并替换一些变量(userSchema, user)根据您的集合架构

userSchema.pre('save', function(next) {
    var currentDate = new Date();
    this.updated_at = currentDate;

    if (!this.created_at)
        this.created_at = currentDate;

    var sno = 1;
    var user = this;
    User.find({}, function(err, users) {
    if (err) throw err;
        sno = users.length + 1;
        user.sno = sno;
        next();
    });
});

【讨论】:

  • 这不是一个有效的解决方案。如果从中间删除条目,则多个条目将具有相同的 id,因为您正在获取文档的长度并增加 1。stackoverflow.com/questions/28357965/mongoose-auto-increment
  • 就我而言,我使用的是软删除功能,所以它没有发生。
  • 我正在添加另一个答案,为您提供更多解决方案。
【解决方案2】:

如果您使用软删除功能 上述答案可能有效,但要解决它,有几种方法。 1:在插入新记录之前获取最后一个文档(行)并放入id = 1 + (id of the last record)。 2:可以使用插件mongoose-auto-increment。 3:最后但并非最不重要选项将最后增加的值保存在单独的集合中(集合名称:autoIncrement 列将是集合和 sno),在创建记录之前获取该集合增量的 sno 值它,创建您的记录并在 autoIncrement 集合中再次更新 sno 值。

奖励:

1:可以在redis中创建autoIncrement。

2:这个答案的第一点将无法解决几个问题,即:您的应用会在删除时执行某种行为,如果用户从集合的开头或中间删除一行,它将删除该 id( sno. 表格),但万一用户删除了最后一条记录。它会放那个sno。在下一条记录中。

var CounterSchema = Schema({
    _id: {type: String, required: true},
    seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);

var entitySchema = mongoose.Schema({
    testvalue: {type: String}
});

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-29
    • 2018-12-12
    • 2014-06-10
    • 2015-04-06
    • 2020-06-25
    相关资源
    最近更新 更多