然后复制这里第二个 URL:

在项目根目录的目录配置中,创建一个db.js文件。
mkdir config
cd config
touch db.js在里面,添加刚才的URL:
module.exports = {
url : YOUR URL HERE
};别忘了把你的用户名和密码(来自数据库用户的密码,而不是你的 mLab 帐户)添加到URL中。 (如果你要将此项目提交到 Github 上,请确保包含 .gitignore 文件 像这样,,不要与任何人分享你的密码。)
现在在你的 server.js 中,可以用 MongoClient 连接到数据库了,使用它来包装你的应用程序设置:
// server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err)
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})如果你用的是最新版本的 MongoDB(3.0+),请将其修改为:
// server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err) // Make sure you add the database name and not the collection name
const database = database.db("note-api")
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
这是你的基础架构的最后一个设置!
添加到你的数据库
MongoDB将数据存储在 collections 中。在你的项目中,你希望将笔记存储在一个名为 notes 的 collection 中。
由于将数据库作为路径中的 db 参数传入,因此可以像这样访问它:
db.collection('notes')创建笔记就像在集合上调用 insert 一样简单:
const note = { text: req.body.body, title: req.body.title}
db.collection('notes').insert(note, (err, results) => {
}插入完成后(或由于某种原因失败),要么返回错误或反回新创建的笔记对象。这是完整的









