db.bind('tag', {
inc: function(name) {
console.log('function inc');
this.update({name: name}, {'$inc': {count: 1}}, {upsert: true}, function() {
console.log('inc callback');
});
},
dec: function(name) {
console.log('function dec');
var self = this;
self.update({name: name}, {'$inc': {count: -1}}, {upsert: true}, function() {
console.log('function dec callback');
self.findOne({name: name}, function(error, item){
if (item && item.count <= 0) {
self.remove(item);
}
})
});
},
all: function(callback) {
console.log('function all');
this.find().toArray(callback);
}
});
for (var i = 0; i < 1000; i++) {
db.tag.inc('电影');
}
for (var i = 0; i < 500; i++) {
db.tag.dec('电影');
}
db.tag.all(function(err, data) {
console.log('function all callback');
for (var index in data) {
console.dir(data);
}
})
多运行几次,看输出。会发现所有的操作是串行的。不知道是因为mongo native的驱动本身就是串行的还是因为mongoskin在处理的时候串行的。
为了测试是不是因为mongo native驱动的问题,然后用mongoose写了一个另外类似功能的代码,如下:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TagSchema = new Schema({
name : { type: String, index: true },
count : { type: Number },
});
TagSchema.statics.inc = function(name) {
console.log('function inc');
this.update({name: name}, {'$inc': {count: 1}}, {upsert: true}, function() {
console.log('function inc callback!');
});
}
TagSchema.statics.dec = function(name) {
console.log('function dec');
var self = this;
self.update({name: name}, {'$inc': {count: -1}}, {upsert: true}, function(error) {
console.log('function dec callback');
if (error) {
return;
}
self.findOne({name: name}, function(error, item) {
if (error) {
return;
}
if (item && item.count <= 0) {
item.remove();
}
});
});
}
TagSchema.statics.all = function(callback) {
console.log('function all');
this.find().desc('count').exec(callback);
}
var Tag = mongoose.model('Tag', TagSchema);
mongoose.connect('mongodb://localhost/testdb2');
for (var i = 0; i < 1000; i++) {
Tag.inc('电影');
}
for (var i = 0; i < 500; i++) {
Tag.dec('电影');
}
Tag.all(function(err, data) {
console.log('function all callback');
for (var index in data) {
console.dir(data);
}
})
任然是运行看结果。你会发现,mongoose不是串行的。