node.js - 使用 Mongoose 进入快速路由文件

标签 node.js mongodb express mongoose

我正在使用 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 文件中删除导入的路由。然后导出 Mongoose 。

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

module.exports = mongoose;

然后您可以导入 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)

关于node.js - 使用 Mongoose 进入快速路由文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910351/

相关文章:

javascript - 连接一段时间后 Redis ETIMEDOUT 错误

node.js - 如何避免阻塞 node.js 中的主线程?

Node.JS:重用套接字?

node.js - 在 MongoDB 中建模访问控制

MongoDb如何按月和年聚合

javascript - 我的 https 网站在 google auth 重定向到 http 后

node.js - Node.js 中的网页缓存困惑

regex - MongoDB/PyMongo : how to 'escape' parameters in regex search?

node.js - Nodejs 和 Handlebars - 刷新时列表重复,而不是刷新

Node.JS GET/参数