【发布时间】:2014-12-22 22:36:55
【问题描述】:
如果不存在,我的目标是在数据库中插入一个新国家(带有递增的 country_id)。在这种情况下,我尝试获取最大的 country_id 并插入一个 country_id + 1 的新国家/地区。否则我什么都不做。
readFile 是对 readfile 的承诺, filetoArray 将该文件内容更改为数组, processMap 处理每个数组元素并决定我们是否将信息存储到 mongodb
问题是:
promise.promisifyAll(Country.findOne({}).sort({'zid' : -1}).exec()
即使某些数据已经插入数据库,也总是给我相同的结果...
非常感谢任何建议。谢谢。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CountrySchema = new Schema({
zn: {type: String, required: true},
zid: {type: Number, required: true}
});
var promise = require('bluebird');
function processMap(data){
return promise.bind(data).then(insertCountry);
}
var insertCountry = function() {
var googledata = this; // from bind promise
return promise.promisifyAll(Country.findOne({zn: googledata.country}).exec())
.then(function(dbdata){ return {dbdata: dbdata, googledata: googledata}; })
.then(insertCountryIfNotExist)
}
var insertCountryIfNotExist = function(data){
return promise.promisifyAll(Country.findOne({}).sort({'zid' : -1}).exec())
.then(function(d){
var newc = new Country({zn: data.googledata.country, zid: d.zid + 1});
return promise.promisifyAll(newc.saveAsync())
});
}
// main code is here
readFile(file)
.then(filetoArray)
.map(processMap, {concurrency: 1}) // end of then
.then(function(data){
console.log('done');
})
【问题讨论】:
-
Promisify 模型本身,如
Promise.promisifyAll(mongoose.model('Country')),然后使用添加的Async方法(如findOneAsync)
标签: node.js map mongoose promise bluebird