3 回答

TA貢獻1836條經驗 獲得超5個贊
這是一個示例,如何在Mongoose中實現(xiàn)自動遞增字段:
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();
});
});

TA貢獻1829條經驗 獲得超9個贊
您可以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一次。

TA貢獻1784條經驗 獲得超9個贊
投票最多的答案不起作用。解決方法是:
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;
? ? });
});
該選項的參數為您提供了更新的結果,如果它不存在,它會創(chuàng)建一個新文檔。
添加回答
舉報