Node.js 在express route文件中使用Mongoose
我正在使用Mongo开发一个express应用程序,代码如下:Node.js 在express route文件中使用Mongoose,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我正在使用Mongo开发一个express应用程序,代码如下: 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");
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;
如何将Mongoose用于以前初始化的index.js
文件
谢谢大家 您的导入方式不对。从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;
嗨,杰克!对不起,我不明白你的答案。。。我的第一个代码片段是Express的索引脚本。那么,我将如何要求将索引文件输入到路由器中呢首先,我绝对建议您将连接提取到它自己的文件中,这样您就可以将其导入任何您想要的地方。但是,在您的情况下,您不需要导入它,只需将我编写的
connection.find({})
替换为mongoose.find({})
就可以了!我已经添加了一个示例,说明如何拆分代码以使其更易于管理OK,明白了!但是如果我多次使用mongoose\u connection.js
导入它,我会与MongoDB建立多个连接吗?不,它将共享同一个连接!如果不能创建多个模式,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)