我试图设置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
,因为程序继续进行而不等待查询完成。
有人可以帮我解决这个问题吗?
使用事件调度和监听器在异步调用的情况下。 –
你需要承诺。 –