我真的很困惑變量範圍問題,需要通過配置文件中的路徑文件。爲什麼我的Mongoose模式方法在從模型文件中調用時「看到」所需的對象,但從我的app.js
文件中調用時卻沒有?我相信我一定會做出明顯錯誤的事情,但我看不到它。爲什麼我的Mongoose模式方法「不能」看到我需要的對象?
節點項目有以下(簡化的)結構:
|models
-index.js
-story.js
-post.js
-app.js
-config.js
這是config.js:
config = {};
config.test = 'test';
config.models = __dirname + '/models';
module.exports = config;
這是story.js:
var config = require('../config.js');
var models = require(config.models);
var foo = {};
foo.bar = 'baz';
var storySchema = mongoose.Schema
({
author: {type: mongoose.Schema.Types.ObjectId},
root: {type: mongoose.Schema.Types.ObjectId, default: null}
});
storySchema.methods.test = function()
{
console.log(foo.bar);
console.log(config.test);
console.log(models);
}
var Story = exports.model = mongoose.model('story', storySchema);
當我在app.js中創建一個新的Story
,並調用它的test()
方法,我得到這個輸出:
baz
(所以我知道這是看到在同一個文件對象)
test
(所以我知道這是看到在配置文件中的變量)
{}
(「本應該」記錄我的模型對象,但它記錄一個空的對象,爲什麼?)
當我創建story.js
文件中的新Story
對象,並運行它(node ./models.story.js
)返回的預期值(模型對象被記錄,而不是一個空的對象)。
更新,這裏有index.js和app.js文件:
index.js:
module.exports = {
post: require('./post'),
story: require('./story')
};
app.js:
var config = require('./config');
var models = require(config.models);
var story = new models.story.model();
story.test();
這導致類似但不同的意外行爲。如果我在'app.js'和'story.js'中進行更改並更改'require'調用,那麼現在如果從'app.js'和'baz調用方法,我會得到'baz,undefined,undefined',測試...'接着是預期的結果(我的模型對象的轉儲)。現在更加困惑。完全不同的行爲取決於創建對象的位置。現在,顯然如果對象是在story.js中創建的,它可以看到'config.js',但是如果它是在'app.js'中創建的,則可以看到'config.js'。 –