【问题标题】:Set a javascript object property in a constructor with mongoose.find() method使用 mongoose.find() 方法在构造函数中设置 javascript 对象属性
【发布时间】:2015-08-12 03:23:33
【问题描述】:

我正在尝试设置我的 Flight 对象的 _docs 属性与从我的猫鼬查询返回的文档,然后根据 _docs 属性定义其他两个属性,但我无法这样做是因为它是异步发生的。我已经尝试过回调、promise 和 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!!
                             }

我尝试了很多不同的方法。因此,当它不返回猫鼬对象时,我只得到对象中的flightId,其余的是undefined,因为程序无需等待查询完成即可继续运行。

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 在异步调用的情况下使用事件调度器和监听器。

标签: javascript node.js mongodb asynchronous mongoose


【解决方案1】:

这是我的建议:

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

【讨论】:

  • 我刚刚尝试过,但我仍然遇到异步问题,当我尝试 console.log(flight._docs) 时,我得到未定义,因为查询需要一段时间,程序无需等待即可继续完成查询。
  • 我担心你的概念是错误的。这是反应式/异步编程的含义,当你等待时事情会继续进行,例如从数据库中读取的值。如果你想将你的猫鼬访问与你程序的其他部分同步,你必须从你的 Flight 构造函数中取出 VolDoc.find 调用并同步它。您可以使用 async github.com/caolan/async 或 Kris Kovolskis Q Lib github.com/kriskowal/q 来支持您。
  • 我编辑了我的答案。这是未经测试的代码。可能有错误。它应该会给你一个提示。
  • 好的,非常感谢它可以工作,但是没有办法直接在构造函数中定义所有属性吗?这样我只需要输入 new Flight('qwertz') 我的对象就准备好了?
  • 不,没有,因为猫鼬是异步的。对 find 方法的调用不会阻塞并等待数据可用。这就是为什么您提供一个所谓的回调函数,当数据可用时调用该函数。我不知道对 mongodb 的同步调用。
猜你喜欢
  • 1970-01-01
  • 2013-12-10
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多