2014-10-27 86 views
0

我的目标是插入一个新的国家(增加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'); 
}) 
+2

Promisify模型本身,如在'Promise.promisifyAll(mongoose.model( '国家'))',然后使用加入'Async'方法(如'findOneAsync') – aarosil 2014-10-27 17:46:21

回答

1

其实Exec的返回从mpromise继承了promise,没有必要在你的情况下使用的蓝鸟,或者如果你想使用蓝鸟,那么请不要混用具有蓝色鸟猫鼬的承诺。

一些示例:

var insertCountry = function() { 
    var googledata = this; 
    return Country.findOne({zn: googledata.country}).exec() 
    .then(function(dbdata){ 
     return {dbdata: dbdata, googledata: googledata}; 
    }) 
    .then(function(data){ 
     return Country.findOne({}).sort({'zid' : -1}).exec() 
      .then(function(d){ 
      var newc = new Country({zn: data.googledata.country, zid: d.zid + 1}); 
      return newc.save(); 
     }) 
    }) 
} 
+0

非常感谢!让我测试这个更多的案件! – 2014-10-28 00:39:31

+0

另一个问题。我声明了一个函数:getmaxcid = Country.findOne({})。sort({'zid':-1})。exec();并替换上面的代码以返回getmaxcid.then(d){xxxx}。这不起作用。你能告诉我这里发生了什么吗? (这是否意味着你不能声明函数和重用代码...?) – 2014-10-28 01:05:58

+1

对不起,我需要定义一个函数,每当你使用数据/ params从承诺 – 2014-10-28 01:13:18