[英]Set a javascript object property in a constructor with mongoose.find() method
我正試圖設置從我的貓鼬查詢返回的文檔來設置我的Flight
Object的_docs
屬性,然后基於_docs
屬性定義另外兩個屬性,但是我無法做到這一點,因為它異步發生。 我已經嘗試過回調,promise和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!!
}
我嘗試了許多不同的方法。 因此,當它不返回貓鼬對象時,我只會在對象中獲得flightId
,而其余的則是undefined
因為程序會繼續運行而無需等待查詢完成。
有人可以幫我解決這個問題嗎?
這是我的建議:
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');
}
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.