2015-05-29 74 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

我引导了我的答案。这是未经测试的代码。可能有错误。它应该给你一个提示。 –

相关问题