2014-10-27 89 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