我正在尝试以有序的方式将数组插入到mongodb数据库中,为此我正在使用async.eachSeries,但是行没有按照数组中的顺序插入。这是代码:
https://gist.github.com/r01010010/af8eeb39023ce1cc04f6#file-series-js-L16
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true, safe: true});
var db = new mongodb.Db('scjs', server);
db.open(function(err, db) { if(err) throw err;
async.eachSeries(
// Collection
mongo_provinces
// Iterator
, function(province, done){
db.collection('provinces').insert(province, function(err, result) { if(err) throw err;
console.log(result);
done();
});
}
// Callback when the iteration is finished
, function(err){ if(err) throw err;
process.exit();
}
);
});
我不会在这里依赖插入顺序,而是依赖于检索。如果未指定排序,则默认查询将按自然顺序返回文档。如果要按特定顺序获取结果,请应用排序参数:
- 使用排序:http://docs.mongodb.org/manual/reference/method/cursor.sort/#cursor.sort
- 自然顺序:http://docs.mongodb.org/manual/reference/method/cursor.sort/#return-in-natural-order