使用mongoose.find()方法在构造函数中设置javascript对象属性

Set a javascript object property in a constructor with mongoose.find() method

本文关键字:设置 javascript 对象 属性 构造函数 find mongoose 方法 使用      更新时间:2023-09-26

我试图设置设置我的Flight对象的_docs属性与从我的猫鼬查询返回的文档,然后根据_docs属性定义另外两个属性,但我不能这样做,因为它异步发生。我试过回调,承诺和npm async,但我没有得到它的工作。

我对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,因为程序继续运行而不等待查询完成。

谁能帮我解决这个问题?

我的建议是:

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');
  }
]);