我尝试设置使用我的mongoose查询中返回的文档设置_docs
对象的Flight
属性,然后根据_docs
定义另外两个属性财产,但我不能这样做,因为它是异步发生的。我尝试过回调,承诺和npm异步,但我不能让它工作。
我对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!!
}
我尝试了很多不同的方法。因此,当它没有返回mongoose对象时,我只获得对象中的flightId
,其余为undefined
因为程序继续而不等待查询完成。
有人可以帮我解决这个问题吗?
答案 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');
}
]);