我试图在mongodb中实现自动递增字段,如文档(http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/)中所强调的那样。但是,我不确定在猫鼬中最好的方法是什么。
我有一个CounterSchema和一个UserSchema,我想知道在哪里放置getNextSequence函数,以及如何从用户架构调用它?
//counter.js
var CounterSchema = new Schema({
category: String,
seq: Number
});
//done in mongo shell
db.counters.insert({category: 'userIndex', seq: 0})
//user.js
var UserSchema = new Schema({
name: String,
UserIndex: Number
}
//per mongodb docs -> not sure where I should insert it
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
答案 0 :(得分:0)
尝试像这样预先保存异步中间件
User.pre('save', true, function(next, done){
var self = this;
var Autoincrement = mongoose.model('Autoincrement');
if (self.isNew){
Autoincrement.getNext(function(err, val){
if (err) return done(err);
self.auto = val;
done();
});
}else{
// done should be called after next
setTimeout(done,0);
}
next();
});