2015-05-29 77 views
0

我試圖設置Flight對象的_docs屬性,使用從我的貓鼬查詢中返回的文檔,然後定義兩個基於_docs屬性,但我無法做到這一點,因爲它發生異步。我已經嘗試過回調,承諾和NPM異步,但我沒有得到它的工作。在構造函數中使用mongoose.find()方法設置javascript對象屬性

我對JavaScript比較陌生,並且有一些問題需要正確理解異步概念。我正在使用node.js.

這裏就是我想要做的事:

var mongoose = require('mongoose'); 
mongoose.connect('mongodb://*******:******@localhost:27017/monitoring'); 
var db = monk('localhost:27017/monitoring', {username: '********',password: '*******'}); 
var VolDoc = require('./model/voldoc.js'); 


var Flight = function(flightId) { 
    this._flightId = flightId; 
    this._docs = VolDoc.find({_id: flightId}, {}, function(e, docs) { 
     return docs; //this._docs should be the same than docs! 
     //here or outside of the query i want do define a BEGIN and END property of the Flight Object like this : 
     //this._BEGIN = docs[0].BEGIN;  
     //this refers to the wrong object! 
     //this._END = docs[0].END; 
    }); 
    //or here : this._BEGIN = this._docs[0].BEGIN; 
    //this._END = this._docs[0].END 
}; 

var flight = new Flight('554b09abac8a88e0076dca51'); 
// console.log(flight) logs: {_flightId: '554b09abac8a88e0076dca51', 
          //_docs: 
          //and a long long mongoose object!! 
          } 

我試過很多不同的方式。所以當它不返回貓鼬對象時,我只在對象中得到flightId,其餘的是undefined,因爲程序繼續進行而不等待查詢完成。

有人可以幫我解決這個問題嗎?

+0

使用事件調度和監聽器在異步調用的情況下。 –

+0

你需要承諾。 –

回答

0

這裏是我的建議:

require('async'); 

var Flight = function(flightId) 
{ 
    this._flightId = flightId; 
}; 

var flight = new Flight("qwertz"); 
async.series([ 
    function(callback){ 
    VolDoc.find({_id:self._flightId},{}, function(e, docs) 
    { 
     flight._docs = docs; 
     flight._BEGIN = docs[0].BEGIN;  
     flight._END = docs[0].END; 
     callback(e, 'one'); 
    });               
    }, 
    function(callback){ 
    // do what you need flight._docs for. 
    console.dir(flight._docs); 
    callback(null, 'two'); 
    } 
]); 
+0

我只是嘗試過,但我仍然有異步的問題,當我嘗試console.log(flight._docs)我得到未定義,因爲查詢需要一段時間,程序繼續而不等待查詢完成。 –

+0

我擔心你的想法是錯誤的。正在等待例如事件繼續進行時,反應/異步編程的意義就在於此。從數據庫讀取的值。如果你想將你的貓鼬訪問與你的其他部分同步,你必須從你的Flight構造函數中取出VolDoc.find調用並同步它。您可以使用async https://github.com/caolan/async或Kris Kowolskis Q Lib https://github.com/kriskowal/q來支持您。 –

+0

我引導了我的答案。這是未經測試的代碼。可能有錯誤。它應該給你一個提示。 –

相關問題