我的目標是插入一個新的國家(增加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