本教程旨在向您展示如何在Express.js应用程序中打开多个MongoDB连接。
现在,我们要创建一个package.json
文件,该文件将跟踪我们的依赖项信息。为此,请创建一个新文件,并将以下内容放入其中:
{
"name": "mongo-conn",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"seed": "node seeder.js",
"dev": "nodemon index.js"
},
"dependencies": {
"express": "^4.17.1",
"faker": "^4.1.0",
"mongoose": "^5.9.7",
"nodemon": "^2.0.2"
}
}
让我们创建一个新文件并将其命名index.js
。该文件将保存我们的主服务器代码。将以下内容放入index.js
文件中:
const express = require('express');
const {userModel, todoModel} = require('./models');
const app = express();
app.get('/users', async (req, res) => {
const users = await userModel.find({});
res.json(users);
});
app.get('/todos', async (req, res) => {
const todos = await todoModel.find({});
res.json(todos);
});
const port = 3000;
app.listen(port, () => console.log(`App listening at http://localhost:${port}`));
现在,我们将创建一个新文件并调用它connections.js
,并将以下内容放入其中:
const mongoose = require('mongoose');
function makeNewConnection(uri) {
const db = mongoose.createConnection(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
db.on('error', function (error) {
console.log(`MongoDB :: connection ${this.name} ${JSON.stringify(error)}`);
db.close().catch(() => console.log(`MongoDB :: failed to close connection ${this.name}`));
});
db.on('connected', function () {
mongoose.set('debug', function (col, method, query, doc) {
console.log(`MongoDB :: ${this.conn.name} ${col}.${method}(${JSON.stringify(query)},${JSON.stringify(doc)})`);
});
console.log(`MongoDB :: connected ${this.name}`);
});
db.on('disconnected', function () {
console.log(`MongoDB :: disconnected ${this.name}`);
});
return db;
}
const userConnection = makeNewConnection('mongodb://127.0.0.1:27017/user');
const todoConnection = makeNewConnection('mongodb://127.0.0.1:27017/todo');
module.exports = {
userConnection,
todoConnection,
};
现在让我们创建另一个文件并调用它models.js
,并将以下内容放入其中:
const mongoose = require('mongoose');
const {userConnection, todoConnection} = require('./connections');
const userSchema = new mongoose.Schema({
name: String,
isActive: Boolean,
}, {
versionKey: false,
timestamps: true,
});
const todoSchema = new mongoose.Schema({
title: String,
completed: Boolean,
}, {
versionKey: false,
timestamps: true,
});
const userModel = userConnection.model('User', userSchema);
const todoModel = todoConnection.model('Todo', todoSchema);
module.exports = {
userModel,
todoModel,
};
现在让我们创建另一个文件并命名seeder.js
,并将以下内容放入其中:
const faker = require('faker');
const {userModel, todoModel} = require('./models');
const {userConnection, todoConnection} = require('./connections');
async function seed() {
for (let i = 0; i< 10; i++) {
await userModel.create({
name: faker.name.findName(),
isActive: faker.random.boolean(),
});
}
for (let i = 0; i < 10; i++) {
await todoModel.create({
title: faker.lorem.words(3),
completed: faker.random.boolean(),
});
}
}
seed().then(() => {
userConnection.close();
todoConnection.close();
});
现在打开您的终端并使用以下命令播种数据库:
yarn seed
让我们通过在终端中运行以下命令来启动应用程序:
yarn dev
现在,在浏览器中打开以下链接:
http://localhost:3000/users
您可以在我的GitHub个人资料中找到此应用程序的完整源代码: