【问题标题】:Unable to use Mongoose Object Methods from non-Mongoose Object无法使用来自非 Mongoose 对象的 Mongoose 对象方法
【发布时间】:2016-02-18 22:24:17
【问题描述】:

假设我们有一个 Mongoose 对象Foo.js

var mongoose = require('mongoose');

var Bar = require('/path/to/bar');

var Foo = mongoose.Schema({});

Foo.statics.hello = function() {
  console.log('hello from foo');
};

Foo.statics.useBar = function() {
  Bar.hello();
};

module.exports = mongoose.model('Foo', Foo);

以及常规的 javascript 对象 Bar.js

var Foo = require('/path/to/foo');

var Bar = function() {};

Bar.hello = function() {
  console.log('hello from bar');
};

Bar.useFoo = function() {
  Foo.hello();
};


module.exports = Bar;

如果我们想从Foo 调用Bar 中的方法,一切都会好起来的。然而,如果我们想从Bar 调用Foo 中的方法,我们会收到一个错误。

app.use('/test', function(req, res, next) {

  var Foo = require('/path/to/foo');
  var Bar = require('/path/to/bar');

  Foo.hello();
  Bar.hello();

  Foo.useBar();
  Bar.useFoo();

});

以上产出:

hello from foo
hello from bar
hello from bar
TypeError: Foo.hello is not a function

为什么会这样?

另外,我如何创建一个对象Bar,它可以从Foo 调用方法,但同时又不应该——也不能——持久化到mongodb?

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    您遇到的问题是 node.js 中的循环/循环依赖关系。它给你一个空对象。

    如果您像这样更改Bar.js

    var Bar = function() {};
    module.exports = Bar;
    
    var Foo = require('/path/to/foo');
    
    Bar.hello = function() {
      console.log('hello from bar');
    };
    
    Bar.useFoo = function() {
      Foo.hello();
    };
    

    然后将 app.use 中的顺序交换为

    var Bar = require('/path/to/bar');
    var Foo = require('/path/to/foo');
    

    它对我有用。

    查看此答案以获取更多信息:How to deal with cyclic dependencies in Node.js

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-22
      • 2018-08-15
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 2017-10-09
      • 2018-06-01
      • 2021-05-29
      相关资源
      最近更新 更多