猫鼬自动递增

根据此mongodb文章,可以自动增加字段,我想使用counters收集方式。


该示例的问题在于,我没有成千上万的人使用mongo控制台在数据库中键入数据。相反,我正在尝试使用猫鼬。


所以我的架构看起来像这样:


var entitySchema = mongoose.Schema({

  testvalue:{type:String,default:function getNextSequence() {

        console.log('what is this:',mongoose);//this is mongoose

        var ret = db.counters.findAndModify({

                 query: { _id:'entityId' },

                 update: { $inc: { seq: 1 } },

                 new: true

               }

        );

        return ret.seq;

      }

    }

});

我已经在同一数据库中创建了counters集合,并添加了一个带有'entityId'的_id的页面。从这里,我不确定如何使用猫鼬更新该页面并获取递增编号。


没有计数器的架构,我希望它保持这种状态,因为这实际上不是应用程序使用的实体。仅应在模式中使用它来自动递增字段。


慕森卡
浏览 627回答 3
3回答

HUX布斯

这是一个示例,如何在Mongoose中实现自动递增字段: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();    });});

湖上湖

您可以mongoose-auto-increment按以下方式使用包:var mongoose      = require('mongoose');var autoIncrement = require('mongoose-auto-increment');/* connect to your database here *//* define your CounterSchema here */autoIncrement.initialize(mongoose.connection);CounterSchema.plugin(autoIncrement.plugin, 'Counter');var Counter = mongoose.model('Counter', CounterSchema);您只需要初始化autoIncrement一次。

HUWWW

投票最多的答案不起作用。解决方法是:var CounterSchema = new mongoose.Schema({    _id: {type: String, required: true},    seq: { type: Number, default: 0 }});var counter = mongoose.model('counter', CounterSchema);var entitySchema = mongoose.Schema({    sort: {type: String}});entitySchema.pre('save', function(next) {    var doc = this;    counter.findByIdAndUpdateAsync({_id: 'entityId'}, {$inc: { seq: 1} }, {new: true, upsert: true}).then(function(count) {        console.log("...count: "+JSON.stringify(count));        doc.sort = count.seq;        next();    })    .catch(function(error) {        console.error("counter error-> : "+error);        throw error;    });});该选项的参数为您提供了更新的结果,如果它不存在,它会创建一个新文档。您可以在此处查看官方文档。如果您需要排序索引,请查看此文档
打开App,查看更多内容
随时随地看视频慕课网APP