Mongodb in Express
Mongodb in Express
Mongodb
非关系形数据库
npm install mongodb
在express项目中安装;
- Usage
全局数据库连接db.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017/config'; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, poolSize: 10, });
async function connect() { try { await client.connect() console.log('has Connect') } catch (e) { console.error(e) } }
connect().then();
module.exports = client
|
调用数据库连接并请求数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const client = require('../utils/db') const express = require('express') const app = express()
app.get('/', function(req, res, next) { const db = client.db(); db.collection('user').find().toArray((err, docs) => { if (err) { console.error(err); res.status(500).send('Failed to query users from MongoDB'); return; } console.log('Found users:', docs); res.send(docs); }); });
|