使用猫鼬到快速路由文件中

时间:2018-10-20 21:39:06

标签: node.js mongodb express mongoose

我正在与Mongo一起开发一个快速应用程序,我有以下代码:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

import indexRoute from './routes/index'; ... let db = mongoose.connection; db.on('error', console.error.bind(console, 'MongoDB connection error:')); db.once('open', function() { console.log("Connected to MongoDB"); ... app.use('/v1', indexRoute); ... }); 如下:

./routes/index.js

如何在先前初始化的import express from 'express'; const router = express.Router(); router.get('/', (req, res) => { // I NEED TO USE MONGOOSE HERE ... res.json({resp}); }); ... export default router; 文件中使用猫鼬?

谢谢大家!

1 个答案:

答案 0 :(得分:1)

您的导入方式有误。从猫鼬文件中删除导入的路由。然后出口猫鼬。

const mongoose = require('mongoose');
let db = mongoose.connection;
mongoose.connect(
    'mongodb://localhost:27017/your-db',
    options,
    err => {
      console.log(err);
  },
);

module.exports = mongoose;

然后,您可以导入猫鼬并按预期使用它。

import express from 'express';
import connection from './mongoose.js' // Or what ever / wherever the above file is.
const router = express.Router();
router.get('/', (req, res) => {
  connection.find({}).then(model => {   // <-- Update to your call of choice.
      res.json({model});
  });
});
export default router;

如果您想了解更多信息,Mozilla在这里有一个很好的教程:

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose

编辑

文件结构示例如下

 - database
     - mongoose_connection.js <-- where top code section goes
 - Router
     - routes.js <-- where you put your router information from second code section
 - index.js <-- Where the entry point to your application is.

然后在索引中使用

import routes from './router/routes'
express.use('/', routes)
相关问题