繁体   English   中英

使用 Mongoose 进入快速路由文件

[英]Use Mongoose into a express route file

我正在使用 Mongo 处理快速应用程序,我有以下代码:

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;

如何在之前初始化的index.js文件中使用 Mongoose?

谢谢大家!

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM