我的目标是插入一个新的国家(增加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( '国家'))',然后使用加入'Async'方法(如'findOneAsync') – aarosil 2014-10-27 17:46:21