Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.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
Node.js 使用路由、控制器和模型重构NodeJS项目的中间件代码_Node.js_Mongodb_Optimization_Refactoring_Project Structure - Fatal编程技术网

Node.js 使用路由、控制器和模型重构NodeJS项目的中间件代码

Node.js 使用路由、控制器和模型重构NodeJS项目的中间件代码,node.js,mongodb,optimization,refactoring,project-structure,Node.js,Mongodb,Optimization,Refactoring,Project Structure,我目前很难构建我的NodeJS项目。我关注了几个YouTube系列,看到人们使用不同的技术来构建他们的代码。在我的情况下,你会建议我采用哪种结构?什么是最佳实践 我有我的app.js,其中包括建立到MongoDB的连接,初始化express、bodyParser、作为视图引擎的pug,最后启动服务器 我的router.js包含所有路由,不幸的是,还包含一些中间件代码,我希望将它们移动到自己的专用控制器中 models文件夹保存MongoDB的所有模式文件 // File structure: .

我目前很难构建我的NodeJS项目。我关注了几个YouTube系列,看到人们使用不同的技术来构建他们的代码。在我的情况下,你会建议我采用哪种结构?什么是最佳实践

我有我的
app.js
,其中包括建立到MongoDB的连接,初始化express、bodyParser、作为视图引擎的pug,最后启动服务器

我的
router.js
包含所有路由,不幸的是,还包含一些中间件代码,我希望将它们移动到自己的专用控制器中

models
文件夹保存MongoDB的所有模式文件

// File structure:
.
├─ controllers
|  ├─ morticians.js
|  ├─ people.js
|  └─ pickups.js
├─ models
|  ├─ mortician.js
|  ├─ person.js
|  └─ pickup.js
├─ views
|  ├─ elements
|  |  └─ ..
|  ├─ pages
|  |  ├─ dashboard.pug
|  |  └─ ..
|  └─ layout.pug
├─ app.js
└─ router.js
我们是医院,有时这里会有人死亡。一个殡仪员来接他们,但将此人从我们的系统中移除的过程还没有自动化。这就是这个webapp的用途。从我们的数据库中提取所有死者,在webapp中显示他们,并在殡仪员来接那个人时将其删除

1。当请求主页时,它会找到所有人,然后是MongoDB的所有殡仪师,最后呈现页面。我可以想象,这不是最佳实践,但如何重构它呢

// snippet router.js
const Person= require('./models/person')
const Mortician = require('./models/mortician')
router.get('/', (req, res, next) => {
  Person.find({ pickedUp: false }, (err, people) => {
    Mortician.find({}, (err, morticians) => {
      if (err) return console.log(err);
      res.render('pages/dashboard', {
        title: 'Dashboard',
        persons: people,
        morticians: morticians
      })
    })
  })
}
我尝试将MongoDB操作移动到它们的
控制器
文件中,如下所示。它起作用了,但我不确定,因为它使用了多个承诺,并没有真正简化事情:

// snippet router.js
const ConPeople = require('./controllers/people')
const ConMorticians = require('./controllers/morticians')
router.get('/',
  (req, res, next) => {
    res.locals.options = { pickedUp: false }
    ConPeople.find(req, res, next)
      .then((people) => {
        res.locals.people = people
        next()
      })
  },
  (req, res, next) => {
    res.locals.options = {}
    ConMorticians.find(req, res, next)
      .then((morticians) => {
        res.locals.morticians = morticians
        next()
      })
  },
  (req, res) => {
    res.render('pages/dashboard', {
      title: 'Dashboard',
      people: res.locals.people,
      morticians: res.locals.morticians.reverse()
    })
  }
)

// snippet controllers/people.js
module.exports = {
  find: (req, res, next) => {
    return Person.find(res.locals.options)
  }
}

2.在某些情况下,我需要执行命令,如从MongoDB删除或添加人员。例如,一个殡仪员来接一个人。我需要将此人的状态设置为
pickedUp=true
,如果提供了,最终添加一名新的殡仪员,并将一份新文档添加到收藏
pickups
。我如何做到这一点而不必重写相同的行?

有两件事,当结合使用时,会使代码变得更好:

  • Collection.find
    返回一个承诺
  • 要等待承诺在现代Javascript中得到解决,请使用
    wait
您可以使用以下代码:

const Person= require('./models/person')
const Mortician = require('./models/mortician')
router.get('/', async (req, res, next) => {
  try {
    const persons = await Person.find({ pickedUp: false });
    const morticians = await Mortician.find({});
    res.render('pages/dashboard', {
      title: 'Dashboard',
      persons,
      morticians,
    });
  } catch(e) {
    // handle errors
  }
});
或者,要以并行方式而不是串行方式检索结果,请使用
Promise.all

router.get('/', async (req, res, next) => {
  try {
    const [persons, morticians] = await Promise.all([
      Person.find({ pickedUp: false }),
      Mortician.find({})
    ]);
    res.render('pages/dashboard', {
      title: 'Dashboard',
      persons,
      morticians,
    });
  } catch(e) {
    // handle errors
  }
});
只要有多个异步调用要执行,就可以使用相同类型的模式—不需要难看的括号嵌套和缩进