1.安装MongoDB驱动程序
在Node.js应用程序中连接MongoDB,需要使用MongoDB的官方驱动程序。可以使用npm包管理器安装它,命令如下:
//初始化
npm init -y
//依赖包
npm install mongodb
2.连接MongoDB数据库
使用MongoDB驱动程序连接MongoDB数据库。您需要指定MongoDB服务器的URL,数据库的名称以及可选的选项。以下是一个连接MongoDB数据库的示例代码
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myproject';
const client = new MongoClient(url, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("myproject").collection("documents");
client.close();
});
在此示例中,使用MongoClient对象连接到名为"myproject"的数据库。
3.编写API接口
现在,您可以使用Express框架编写API接口。以下是一个使用Express框架创建一个获取所有文档的API接口的示例代码
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myproject';
const app = express();
app.get('/documents', (req, res) => {
MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
if (err) throw err;
const db = client.db('myproject');
const collection = db.collection('documents');
collection.find({}).toArray((err, docs) => {
if (err) throw err;
res.send(docs);
client.close();
});
});
});
app.listen(3000, () => console.log('App listening on port 3000!'));
在此示例中,使用Express框架创建了一个API接口,使用MongoClient对象连接到名为"myproject"的数据库,并从文档集合中检索所有文档并将其返回给客户端。