1

我在为控制器命名以加载我的模型时遇到问题:

我的 app.js

var express = require('express');
var app = express();
app.everyauth = require('everyauth');
app.mongoose = require('mongoose');

var fs = require('fs');

var config = require('./config.js')(app, express);

//Include models
var models = {};
fs.readdir(__dirname + '/models', function(err, files){
    if (err) throw err;
    files.forEach(function(file){
        var name = file.replace('.js', '');
        models.name = require('./models/' + name)(app.mongoose).model;
    });
});

//Include controllers
fs.readdir(__dirname + '/controllers', function(err, files){
    if (err) throw err;
    files.forEach(function(file){
        var name = file.replace('.js', '');
        require('./controllers/' + name)(app, models);
    });
});

app.listen(process.env.PORT || 3000);

例如,我在模型中有 test.js

如果我想在我的数据库中找到一些东西,我想做:

models.test.find({}, function(err, docs){});

但它不起作用,因为测试是未知的,我应该做

models.name.find({}, function(err, docs){});

所以我会用模型的名称替换名称

谢谢

4

1 回答 1

3

试试这个;

models[name] = require('./models/' + name)(app.mongoose).model;

如果要读取目录同步模式,可以使用

var models = {};
var files = fs.readdirSync(__dirname + '/models');
for(var i in files) {
  var name = files[i].replace('.js', '');
  models[name] = require('./models/' + name)(app.mongoose).model;
}

// Now, you can use
models.test
于 2012-11-16T21:02:15.063 回答