Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法从非Mongoose对象使用Mongoose对象方法_Javascript_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Javascript 无法从非Mongoose对象使用Mongoose对象方法

Javascript 无法从非Mongoose对象使用Mongoose对象方法,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,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(); }; modu

假设我们有一个猫鼬对象
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);
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;
以及一个常规javascript对象
Bar.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);
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
为什么会发生这种情况


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

您遇到的问题是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');
它对我有用

有关更多信息,请参阅此答案: