gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:04:37 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com