2016-03-06 79 views
1

我使用node.js和mongoose來獲取一些基於查詢的數據。 Mongoose函數findOne返回一個承諾,它給了我一個javascript對象。我想爲該對象添加一個新字段併爲其賦值,然後應用stringify函數。如果我打印了字符串,我添加的新字段將不會被打印,即使我可以通過該對象訪問它。Javascript新對象字段未保存

model.findOne({},function (err, names) {}) 
     .then(function(data){ 
        response.writeHead(200, {"Content-Type": "application/json"}); 
        data['status'] = 200; 
        data['message'] = 'OK'; 
        response.write(JSON.stringify(data)); 
        response.end(); 
       }, 
       function(err) { 
        response.writeHead(500, {"Content-Type": "application/json"}); 
        var execError = '{"status":500,"message":"'+ err.toString() +'"}'; 
        response.write(execError); 
        response.end(); 
       } 
     ); 

回答

1

我相信你是lean()方法之後,這可以讓你回到一個簡單的查詢鏈的結果文檔的JavaScript版本。它適用於Mongoose而不是創建完整模型實例,然後獲得可修改的完整JavaScript對象。因此,將您的查詢鏈改爲:

var promise = model.findOne().lean(); 
promise.then(function(data){ 
     response.writeHead(200, {"Content-Type": "application/json"}); 
     data['status'] = 200; 
     data['message'] = 'OK'; 
     response.write(JSON.stringify(data)); 
     response.end(); 
    }, 
    function(err) { 
     response.writeHead(500, {"Content-Type": "application/json"}); 
     var execError = '{"status":500,"message":"'+ err.toString() +'"}'; 
     response.write(execError); 
     response.end(); 
    } 
); 
+1

它的工作原理。謝謝。 – Andrew