2014-02-05 30 views
0

我試圖使用template_subject變量作爲subject來發送電子郵件。無法在find()中設置並獲取變量值

當我通過使用findOne &提取數據從mongodb設置變量template_subject。它只是給了我值undefined

我已經從各方面對它進行了測試,數據完美地來自後端,只是它沒有被設置爲variable

有人有這個解決方案?

exports.sendMailMsg = function (templateName, email) { 

var nodemailer = require("nodemailer"); 

var template_subject; 
var template_html;  

Template.findOne({name: templateName}, function (err, template) {  
    template_subject = template.subject; 
    template_html = template.dataMsg; 
}); 

//----- Email Options -----// 
var mailOptions = { 
    from: "Xyz <[email protected]>", // sender address 
    to: email, // list of receivers 
    subject: template_subject, // Subject line 
    html: "<b>Hello,</b><br/><br/> You are successfuly Registered" 
}; 

回答

2

這是因爲findOne函數是異步的,所以在獲取結果時,已經定義了mailOptions變量。 所以也許你可以這樣做:

exports.sendMailMsg = function (templateName, email) { 

var nodemailer = require("nodemailer"); 

var template_subject; 
var template_html;  

Template.findOne({name: templateName}, function (err, template) {  
    template_subject = template.subject; 
    template_html = template.dataMsg; 

    //----- Email Options -----// 
    var mailOptions = { 
     from: "Xyz <[email protected]>", // sender address 
     to: email, // list of receivers 
     subject: template_subject, // Subject line 
     html: "<b>Hello,</b><br/><br/> You are successfuly Registered" 
    }; 

    //Do all the processing here... 
}); 
+0

完美的作品...謝謝 – Anup

相關問題