Upsert 操作
本课属于 Coddy Node.js 学习旅程的“使用 MongoDB 的数据库”单元。第 18 课,共 29 课。
每位读者只给一本书评分一次。再次评分时应该更改星级,而不是再添加一条评分。
使用 { upsert: true } 时,updateOne 会更新与筛选条件匹配的文档;如果没有匹配项,则会根据筛选条件中的字段和更新内容插入一个文档。一次调用即可处理首次评分和之后的每次评分。
// 每个用户对应一个设置文档
await settings.updateOne(
{ user: 'ada' },
{ $set: { theme: 'dark' } },
{ upsert: true }
);筛选条件用于说明如何确定文档的唯一性;这里是每位用户对应一个文档。调用插入文档时,结果中的 upsertedId 会被设置。普通的 insertOne 无法做到这一点:它每次都会添加一个文档。
挑战
简单读者会给书评 1 到 5 星。每位读者对一本书只评分一次:再次评分会更改星级,而不是添加第二条评分。
- 在
server.js中,紧挨着const books = db.collection('books');,打开名为ratings的第二个集合。每条评分都是一个文档:将{ "bookId": "6720a1f4c2b9e81d3a5f0c11", "user": "ada", "stars": 4 }bookId存储为parseId返回的 ObjectId,而不是 URL 中的文本。在 JSON 中,两者看起来一样。 - 添加
PUT /books/:id/ratings。请求体如下:{ "user": "ada", "stars": 4 }。如果这位用户已经给这本书评过分,就更改其星级;如果没有,就添加一条新评分。通过一次调用完成这两种操作。响应状态码为 200,并返回这条评分:{ "user": "ada", "stars": 4 }。 - 添加
GET /books/:id/ratings。响应状态码为 200,并返回该书已存储的评分数组。不能出现其他书的评分:[ { "_id": "6720a1f4c2b9e81d3a5f0c21", "bookId": "6720a1f4c2b9e81d3a5f0c11", "user": "ada", "stars": 2 } ] - 两个路由遇到无效 id 时都使用
parseId,并返回 400。试一试:发送GET /books,并复制 Dune 的_id。发送PUT /books/<Dune's _id>/ratings,请求体为{ "user": "ada", "stars": 4 }:你会收到 200 和{ "user": "ada", "stars": 4 }。再发送一次,请求体改为{ "user": "ada", "stars": 2 }:你会收到 200 和{ "user": "ada", "stars": 2 }。发送GET /books/<Dune's _id>/ratings:你会收到一条评分,是 Ada 给出的 2 星。用{ "user": "bo", "stars": 5 }给 Dune 评分,然后再次列出评分:你会收到两条评分。现在,“Data”选项卡会显示一个ratings集合。GET /books/<Kindred's _id>/ratings会返回[]。
亲手试试
import express from 'express';
import { MongoClient, ObjectId } from 'mongodb';
const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('shelf');
const books = db.collection('books');
await books.createIndex({ isbn: 1 }, { unique: true });
await books.insertMany([
{ title: 'Dune', author: 'Frank Herbert', year: 1965, isbn: '9780441013593', genre: 'scifi' },
{ title: 'Kindred', author: 'Octavia E. Butler', year: 1979, isbn: '9780807083697', genre: 'scifi' },
{ title: 'Emma', author: 'Jane Austen', year: 1815, isbn: '9780141439587', genre: 'classic' },
]);
const app = express();
app.use(express.json());
// 所有错误都返回 { error: message }。
function sendError(res, status, message) {
res.status(status).json({ error: message });
}
// 将 :id 转为 ObjectId;如果 id 无效,则返回 400 响应和 null。
function parseId(req, res) {
if (ObjectId.isValid(req.params.id)) {
return new ObjectId(req.params.id);
}
sendError(res, 400, 'Not a valid id');
return null;
}
app.get('/', (req, res) => {
res.send('Bookshelf API');
});
app.get('/books', async (req, res) => {
const filter = {};
if (req.query.author) {
filter.author = req.query.author;
}
if (req.query.from || req.query.to) {
filter.year = {};
if (req.query.from) {
filter.year.$gte = Number(req.query.from);
}
if (req.query.to) {
filter.year.$lte = Number(req.query.to);
}
}
const list = await books.find(filter).toArray();
res.json(list);
});
app.post('/books', async (req, res) => {
const book = req.body;
try {
await books.insertOne(book);
} catch (err) {
if (err.code === 11000) {
return sendError(res, 409, 'That ISBN is already on the shelf');
}
throw err;
}
res.status(201).json(book);
});
app.get('/books/newest', async (req, res) => {
const n = Number(req.query.n) || 3;
const list = await books
.find({}, { projection: { title: 1, year: 1, _id: 0 } })
.sort({ year: -1 })
.limit(n)
.toArray();
res.json(list);
});
app.get('/books/:id', async (req, res) => {
const id = parseId(req, res);
if (!id) return;
const book = await books.findOne({ _id: id });
if (!book) {
return sendError(res, 404, 'No such book');
}
res.json(book);
});
app.patch('/books/:id', async (req, res) => {
const id = parseId(req, res);
if (!id) return;
const result = await books.updateOne({ _id: id }, { $set: req.body });
if (result.matchedCount === 0) {
return sendError(res, 404, 'No such book');
}
res.json(await books.findOne({ _id: id }));
});
app.post('/books/:id/copies', async (req, res) => {
const id = parseId(req, res);
if (!id) return;
const result = await books.updateOne({ _id: id }, { $inc: { copies: 1 } });
if (result.matchedCount === 0) {
return sendError(res, 404, 'No such book');
}
res.json(await books.findOne({ _id: id }));
});
app.post('/books/:id/tags', async (req, res) => {
const id = parseId(req, res);
if (!id) return;
const result = await books.updateOne({ _id: id }, { $push: { tags: req.body.tag } });
if (result.matchedCount === 0) {
return sendError(res, 404, 'No such book');
}
res.json(await books.findOne({ _id: id }));
});
app.delete('/books/:id', async (req, res) => {
const id = parseId(req, res);
if (!id) return;
const result = await books.deleteOne({ _id: id });
if (result.deletedCount === 0) {
return sendError(res, 404, 'No such book');
}
res.status(204).end();
});
app.listen(3000, () => {
console.log('Bookshelf is running on port 3000');
});
使用 MongoDB 的数据库中的所有课
自己练习: Express 在线编辑器