// note_routes.js
module.exports = function(app, db) {
const collection =
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};试试看!使用 Postman 发送 x-www-form-urlencoded POST 请求,在 Body 选项卡下设置 title 和 body。
响应应如下所示:

如果你登录mLab,你还应该能够在数据库中看到创建的笔记。
READ 路由
现在可以稍微加快步伐。
假设你希望通过导航到 localhost:8000/notes/{id} 来获取刚创建的笔记。这是链接应该是localhost:8000/notes/585182bd42ac5b07a9755ea3。(如果你没有得到其中笔记的 ID,可以通过检查 mLab 或创建一个新的笔记)。
以下是 note_routes.js 中的内容:
// note_routes.js
module.exports = function(app, db) {
app.get('/notes/:id', (req, res) => { });
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};
就像以前一样,你将在数据库 collection 中调用一个方法。在这里,它被恰当地命名为 findOne。
// note_routes.js
module.exports = function(app, db) {
app.get('/notes/:id', (req, res) => {
const details = { '_id': <ID GOES HERE> };
db.collection('notes').findOne(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};你可以通过 req.params.id 从 URL 参数中获取 id。但是,如果你试图将字符串插入上面的
<ID GOES HERE> 位置,它将无法正常工作。MongoDB 不仅要求 ID 为字符串,还要求 ID 是一个对象,它们被之为 ObjectID。
别担心,这很容易解决。这是完整的代码:









